Sha256: aee082ada9b29abe7ee9599532ee45fbd67eae1360e9a78c64f8dd96ec68d16d

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

require 'sad_panda/helpers'

module SadPanda
  # Polarity calculation logic in here
  class Polarity
    include Helpers

    attr_reader :words, :polarities

    def initialize(text)
      @words = words_in(text)
      @polarities = []
    end

    # Main method that initiates calculating polarity
    def call
      words = stems_for(remove_stopwords_in(@words))

      score_polarities_for(frequencies_for(words))

      polarities.empty? ? 5.0 : (polarities.inject(0){ |sum, polarity| sum + polarity } / polarities.length)
    end

    private

    # Checks if words has happy or sad emoji and adds polarity for it
    def score_emoticon_polarity
      happy = happy_emoticon?(words)
      sad = sad_emoticon?(words)

      polarities << 5.0 if happy && sad
      polarities << 8.0 if happy
      polarities << 2.0 if sad
    end

    # Appends polarities of words to array polarities
    def score_polarities_for(word_frequencies)
      word_frequencies.each do |word, frequency|
        polarity = SadPanda::Bank::POLARITIES[word.to_sym]
        polarities << (polarity * frequency.to_f) if polarity
      end

      score_emoticon_polarity
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sad_panda-1.1.0 lib/sad_panda/polarity.rb