我有 5 个文件 file1.txt file2.txt....file5.txt
然后我有 3 个单词的列表 red white blue
我试图找出 red white blue
出现了多少次以及出现在哪些文件中。
最后的格式应该是:
red = file1.txt, file3.txt, 2
white = file2.txt, 1
blue = file1.txt, file2.txt, file3.txt, 3
这是我目前所拥有的:
files.each do |i|
curfile = File.new("#{i}","r")
while (line = curfile.gets)
mywords.each do |j|
if (line ~= /\b#{j}\b/)
##what kind of data structure should I put the results in??
end
end
end
end
我应该把结果放在什么样的数据结构中?
最佳答案
results = {}
%w(red white blue).each do |word|
results[word] = Hash.new(0)
%w(file1.txt file2.txt file3.txt file4.txt file5.txt).each do |file|
scanner = StringScanner.new(File.read(file))
while (scanner.scan_until(/\b#{word}\b/)) do
results[word][file] += 1
end
end
end
这将返回一个散列,其中键是颜色,值是文件名的散列和每个文件中的匹配数:
{'red' => {'file1.txt' => 1, 'file2.txt' => 2}, 'blue' => {'file1.txt' => 1}}
关于ruby - 如何使用 ruby 脚本收集特定类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655223/