class SadPanda::Emotion

Emotion determining logic in here

Attributes

scores[R]
words[R]

Public Class Methods

new(text) click to toggle source
# File lib/sad_panda/emotion.rb, line 10
def initialize(text)
  @words = words_in(text)
  @scores = { anger: 0, disgust: 0, joy: 0,
              surprise: 0, fear: 0, sadness: 0,
              ambiguous: 0 }
end

Public Instance Methods

call() click to toggle source

Main method that initiates scoring emotions

# File lib/sad_panda/emotion.rb, line 18
def call
  words = stems_for(remove_stopwords_in(@words))
  score_words(frequencies_for(words))

  scores.key(scores.values.max)
end
method_missing(emotion) click to toggle source

MethodMissing to implement metods that are the names of each emotion that will returen the score of that specific emotion for the text

# File lib/sad_panda/emotion.rb, line 28
def method_missing(emotion)
  return scores[emotion] || 0 if scores.keys.include? emotion

  raise NoMethodError, "#{emotion} is not defined"
end

Private Instance Methods

ambiguous_score() click to toggle source

Last part of the scoring process If all scores are empty ambiguous is scored as 1

# File lib/sad_panda/emotion.rb, line 38
def ambiguous_score
  unq_scores = scores.values.uniq
  scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero?
end
score_emoticons() click to toggle source
# File lib/sad_panda/emotion.rb, line 58
def score_emoticons
  happy = happy_emoticon?(words)
  sad = sad_emoticon?(words)

  scores[:ambiguous] += 1 if happy && sad
  scores[:joy] += 1 if happy
  scores[:sadness] += 1 if sad
end
score_emotions(emotion, term, frequency) click to toggle source

Increments the score of an emotion if the word exist in that emotion bank

# File lib/sad_panda/emotion.rb, line 45
def score_emotions(emotion, term, frequency)
  return unless SadPanda::Bank::EMOTIONS[emotion].include?(term)

  scores[emotion] += frequency
end
score_words(word_frequencies) click to toggle source

Logic to score all unique words in the text

# File lib/sad_panda/emotion.rb, line 68
def score_words(word_frequencies)
  word_frequencies.each do |word, frequency|
    set_emotions(word, frequency)
  end

  score_emoticons

  ambiguous_score
end
set_emotions(word, frequency) click to toggle source

Iterates all emotions for word in text

# File lib/sad_panda/emotion.rb, line 52
def set_emotions(word, frequency)
  SadPanda::Bank::EMOTIONS.keys.each do |emotion|
    score_emotions(emotion, word, frequency)
  end
end