2010-09-07 23 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