我已讀取的文件,並將它們分割成單詞的數組:顯示信息給用戶
file1 = File.open("spam1.txt","rb")
file1_contents = file1.read
file1 = file1_contents.split(' ')
我可以計算單詞的頻率,使用散列,並
freqs1 = Hash.new(0)
file1.each { |word| freqs1[word] +=1}
freqs1 = freqs1.sort_by {|x,y| y}
freqs1.reverse!
也可以將結果輸出給用戶這樣的:
freqs.each{|word, freq| puts word + ' ' + freq.to_s}
我根據詞的出現次數進行排序想要向用戶顯示消息,如果數組file1
或散列freqs1
包含某些詞多次。
我有一個(壞)主意遍歷freqs1
散列和顯示適當的消息給用戶:
freqs1.each{|word,freq|
if ((word == ('business' || 'fund' || 'funds' || 'account' ||'transfer' || 'money')) && freq > 2) || (word == 'Iraq' && freq > 1) then
puts "File 1 is suspected as spam mail - suspicious word frequency"
else
puts "File 1 does not appear to be spam email"
end
}
然而,這是我傻的,因爲這作用於hash
中的每個元素。
如果像business, fund, funds, account
等字樣出現超過兩次,我怎樣才能向用戶顯示某個消息?
感謝您的任何幫助。
感謝 - 這工作,@Nick Veys是早期的答案,從而不得不接受他的 - 但我喜歡這種方法。 – Tom