gpt4 book ai didi

ruby - 如何从文本文件中读取字符,然后将它们存储到 Ruby 中的散列中

转载 作者:太空宇宙 更新时间:2023-11-03 17:59:22 24 4
gpt4 key购买 nike

我正在做一项作业,但无法弄清楚。我们必须首先解析一个文本文件,然后将结果输入哈希。我这样做了:

    code = File.open(WORKING_DIR + '/code.txt','r')
char_count = {'a' => 0,'b' => 0,'c' => 0,'d' => 0,'e' => 0,'f' => 0,'g' => 0,'h' => 0,'i' => 0,
'j' => 0,'k' => 0,'l' => 0,'m' => 0,'n' => 0,'o' => 0,'p' => 0,'q' => 0,'r' => 0,
's' => 0,'t' => 0,'u' => 0,'v' => 0,'w' => 0,'x' => 0,'y' => 0,'z' => 0
}
# Step through each line in the file.
code.readlines.each do |line|

# Print each character of this particular line.
line.split('').each do
|ch|
char_count.has_key?('ch')
char_count['ch'] +=1
end

我的思路:打开文件到一个名为code的变量阅读各行将线条分成每个字符。我知道这行得通,我可以将角色放到屏幕上。现在我需要将字符输入到散列中,但它不起作用。我在语法(至少)和基本概念(最多)上苦苦挣扎。我只想要文件中的字母字符,而不是标点符号等。

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

我会直接做:

File.open(WORKING_DIR + '/code.txt','r') do |f|
char_count = Hash.new(0) # create a hash where 0 is the default value
f.each_char do |c| # iterate on each character
... # some filter on the character you want to reject.
char_count[c] +=1
end
end

PS:你写了 'ch' 字符串而不是 ch 变量名

编辑:过滤器可以是

f.each_char do |c| # iterate on each character
next if c ~= \/W\ # exclude with a regexp non word character
....

关于ruby - 如何从文本文件中读取字符,然后将它们存储到 Ruby 中的散列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7649970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com