From 5cc29856d25c33762e3fdf8083e2e63e2d49218a Mon Sep 17 00:00:00 2001 From: Nick Legg Date: Mon, 19 Oct 2015 15:50:28 -0400 Subject: [PATCH 1/2] Initial word counter --- count.rb | 40 ++++++++++++++++++++++++++++++++++++++++ count_spec.rb | 26 ++++++++++++++++++++++++++ run.rb | 4 ++++ 3 files changed, 70 insertions(+) create mode 100644 count.rb create mode 100644 count_spec.rb create mode 100644 run.rb diff --git a/count.rb b/count.rb new file mode 100644 index 0000000..bae169d --- /dev/null +++ b/count.rb @@ -0,0 +1,40 @@ +class WordCount + attr_accessor :speech + attr_reader :counted_words + + def load_file(path) + @speech = File.read(path) + end + + def parse_words + @speech.gsub!(/[^0-9a-zA-Z\s]/, '') + @speech.gsub!(/\s+/, ' ') + @speech.downcase!.strip! + @speech = @speech.split(' ') + end + + def count_words + @counted_words = Hash.new + @speech.each do |word| + if @counted_words.include?(word) + @counted_words[word] += 1 + else + @counted_words[word] = 1 + end + end + end + + def report + sorted_words = @counted_words.sort_by { |word, count| count } + sorted_words.reverse_each do |word, count| + puts count.to_s + ' - ' + word + end + end + + def run + load_file('speech.txt') + parse_words + count_words + report + end +end diff --git a/count_spec.rb b/count_spec.rb new file mode 100644 index 0000000..662edc1 --- /dev/null +++ b/count_spec.rb @@ -0,0 +1,26 @@ +require 'rspec' +require_relative 'count' + +describe 'WordCount' do + let(:words) { WordCount.new } + + it "returns text when file is loaded" do + expect(words.load_file('speech.txt')).not_to be_nil + end + + it "speech contains no special characters after parsing" do + words.load_file('speech.txt') + words.parse_words + expect(words.speech =~ /^0-9a-zA-z\s/i).to be nil + end + + it "counts words correctly" do + words.speech = "One two three one two four" + words.parse_words + words.count_words + expect(words.counted_words["one"]).to eq 2 + expect(words.counted_words["two"]).to eq 2 + expect(words.counted_words["three"]).to eq 1 + expect(words.counted_words["four"]).to eq 1 + end +end diff --git a/run.rb b/run.rb new file mode 100644 index 0000000..6f53611 --- /dev/null +++ b/run.rb @@ -0,0 +1,4 @@ +require_relative 'count' + +words = WordCount.new +words.run From 4d127de72082af52a7dc3e194ac8436a92aacaa8 Mon Sep 17 00:00:00 2001 From: Nick Legg Date: Thu, 22 Oct 2015 09:44:48 -0400 Subject: [PATCH 2/2] Use descending sort --- count.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/count.rb b/count.rb index bae169d..a676e7d 100644 --- a/count.rb +++ b/count.rb @@ -25,8 +25,8 @@ def count_words end def report - sorted_words = @counted_words.sort_by { |word, count| count } - sorted_words.reverse_each do |word, count| + sorted_words = @counted_words.sort_by { |word, count| -count } + sorted_words.each do |word, count| puts count.to_s + ' - ' + word end end