I would like to know how it would be possible to 1) Get a txt file as an input. 2) count the no of times a word or words occur! eg say i want to count the no of times good , bad are found in a text file and print it! how would i do this using RUBY?
Asked
Active
Viewed 1,303 times
-1
-
1What's your effort on this problem? – Arie Xiao Mar 13 '14 at 05:22
-
I am new to ruby , I am unable to understand how using (gets) I can get more than one line! I have used .include to match and realize that it matches only the first instance of one of the words. – user3413752 Mar 13 '14 at 05:39
1 Answers
0
Something like this?
word_count = {}
File.open("test.txt", "r") do |f|
f.each_line do |line|
words = line.split(' ').each do |word|
word_count[word] += 1 if word_count.has_key? word
word_count[word] = 1 if not word_count.has_key? word
end
end
end
puts word_count
You could also chuck a check in there to see if it matches a certain word you are looking for or check if they exist in a hash of multiple words you are looking for if you're not interested in everything

dmateos
- 13
- 1
- 5