-
Notifications
You must be signed in to change notification settings - Fork 36
Counting words-Rajashree #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| file = File.open("speech.txt", "r") | ||
| content = file.read | ||
| frequency = Hash.new(0) | ||
| wordcount = content.split(" ") | ||
| wordcount.each do |w| | ||
| w.gsub!(/\W|_/,"") | ||
| frequency[w] += 1 | ||
| end | ||
| frequency = frequency.sort_by {|word,count| count}.reverse | ||
| frequency.each do |key,value| | ||
| puts "#{key}:#{value}" | ||
| end | ||
| file.close | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a pretty good procedural approach that is fine for solving this problem. However, just for fun (and because we have attributes and methods that act on those attributes), how about encapsulating this in a nice WordCounter class that accepts a filepath on initialization and can be asked to print out a word count? 😃 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this work for words containing a single apostrophe? E.g.: it's, another's, that's |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think wordcount might not be the best name for this variable. What is actually being returned here is a list of short strings containing words and punctuation.