2010-09-07 25 views
3

有5个文件file1.txt file2.txt....file5.txt然后我有3个字red white blue我如何收集特定类型的数据与Ruby脚本

我试图找出有多少次,在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 

我应该把什么样的数据结构的结果?

+0

怎么样列出每个颜色的数组中的文件?所以'red = [“file1.txt”,“file3.txt”]'等等。然后,使用'red.length'输出它出现的次数。 – 2010-09-07 02:25:17

+0

作业?使用散列,其中每个键是颜色,并且该键的相关值每增加1次颜色的次数就会加1。 – dawg 2010-09-07 02:28:04

+0

@drewk:询问多维哈希是一个合理的问题。我认为还没有令人满意的答案。 – 2010-09-07 12:46:59

回答

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 
1
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}} 
+0

可能会给出结果自动生成,以至于你不需要'结果[word] = Hash.new(0)'。 – 2010-09-07 12:44:29

+0

是的,我相信可以做'results = Hash.new(Hash.new(0))'。 – 2010-09-07 17:03:26