Skip to content
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

Dan Meehan Solution #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions count.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Counter

def initialize text
@text = text
end

def count
str = @text.downcase
words = []

# Special case to handle first - detect all cases of ' & ' as a word
ampersands = str.scan(/ & /).size
ampersands.times { words << '&' }

# Remove non-word characters, then split on whitespace to get words
str.gsub!(/[^a-zA-Z0-9']/, ' ')
words.concat(str.split)

# Count occurrences of each word
counts = Hash.new(0)
words.each { |w| counts[w] += 1 }
counts.sort_by { |k, v| v }.reverse
end
end

text = File.open('speech.txt', 'r').read
counter = Counter.new(text)
counter.count.each { |w| print "#{w[0]} - #{w[1]}\n" }