Class: Wordstats

Inherits:
Object
  • Object
show all
Defined in:
lib/wordstats.rb,
lib/wordstats/version.rb

Constant Summary collapse

VERSION =
"1.0.3"

Instance Method Summary collapse

Constructor Details

#initializeWordstats

Your code goes here…



6
7
8
# File 'lib/wordstats.rb', line 6

def initialize
  @tagger = EngTagger.new
end

Instance Method Details

#avg_sentence_length(str) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/wordstats.rb', line 68

def avg_sentence_length(str)
  sentence_arr = str.scan(/[^\.!?]+[\.!?]/).map(&:strip)
  sentence_length_arr = []

  sentence_arr.each do |sentence|
    word_arr = sentence.split(' ')
    sentence_length_arr << word_arr.length
  end
  sum = sentence_length_arr.reduce(:+)
  sum / sentence_length_arr.length
end

#avg_word_length(str) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/wordstats.rb', line 23

def avg_word_length(str)
  word_arr = str.split(' ')
  word_length_arr = []
  word_arr.each do |word|
    word_length_arr << word.length
  end
  sum = word_length_arr.reduce(:+)
  sum / word_length_arr.length
end

#most_common_noun(str) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/wordstats.rb', line 33

def most_common_noun(str)
  str = str.downcase
  tagged_str = @tagger.add_tags(str)
  noun_list = @tagger.get_nouns(tagged_str)
  highest_count = 0

  noun_list.each do |k, v|
    if v > highest_count
      highest_count = v
    end
  end

  most_common = noun_list.select {|k, v| v == highest_count}
  most_common.keys
end

#most_common_word(str) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/wordstats.rb', line 49

def most_common_word(str)
  str = str.downcase
  word_list = str.split(' ')

  word_hash = Hash.new(0)
  word_list.each { |key| word_hash[key] += 1 }

  highest_count = 0

  word_hash.each do |k, v|
    if v > highest_count
      highest_count = v
    end
  end

  most_common = word_hash.select {|k, v| v == highest_count}
  most_common.keys
end

#process(str) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/wordstats.rb', line 10

def process(str)
  p "Word Count: " + word_count(str).to_s
  p "Average Word Length: " + avg_word_length(str).to_s
  p "Most Common Noun: " + most_common_noun(str).to_s
  p "Most Common Word: " + most_common_word(str).to_s
  p "Average Sentence Length: " + avg_sentence_length(str).to_s + " words"
end

#word_count(str) ⇒ Object



18
19
20
21
# File 'lib/wordstats.rb', line 18

def word_count(str)
  word_arr = str.split(' ')
  word_arr.length
end