如何使用ruby脚本收集特定类型的数据
我有5个文件如何使用ruby脚本收集特定类型的数据,ruby,file-io,Ruby,File Io,我有5个文件file1.txt file2.txt….file5.txt然后我有3个单词的列表红-白-蓝 我正在试图找出发生了多少次,以及在哪些文件中出现了红-白-蓝 最后,格式应为: 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}","
file1.txt file2.txt….file5.txt
然后我有3个单词的列表红-白-蓝
我正在试图找出发生了多少次,以及在哪些文件中出现了红-白-蓝
最后,格式应为:
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}}
我可以通过以下代码完成此操作:
mystring = ""
colors = %w{red white blue}
final_list = Arrays.new{colors.size}
final_list.each_with_index do |thing,index|
final_list[index] = ""
end
files.each do |i|
File.open("#{i}","r") { |f|
mystring = f.read
}
colors.each_with_index do |thing,index|
pattern = /#{thing}/i
if (mystring =~ pattern)
final_list[index] = final_list[index] + i + " "
end
end
end
colors.each_with_index do |thing,index|
list = final_list[index].split (" ")
puts "#{thing} (#{list.size})= #{list.join(',')}"
end
在数组中列出每种颜色的文件怎么样?所以
red=[“file1.txt”、“file3.txt”]
等等。然后使用red.length
输出它们出现的次数。家庭作业?使用一个散列,其中每个键都是颜色,该键的关联值增加1,表示每种颜色的显示次数。@drewk:询问多维散列是一个合理的问题。我认为ruby还没有一个满意的答案。@drewk你讽刺的问题没有帮助。这不是家庭作业,但即使是……那又怎样?它可能会给出结果
自动动画,这样你就不需要结果[word]=Hash.new(0)
。是的,我相信有可能做到结果=Hash.new(Hash.new(0))
。