Class: Sentimental

Inherits:
Object
  • Object
show all
Defined in:
lib/sentimental.rb

Overview

In an initializer, you can initialize some global defaults:

Sentimental.load_defaults
Sentimental.threshold = 0.1

Then create an instance for usage:

analyzer = Sentimental.new
analyzer.get_sentiment('I love your service')
=> :positive

You can make new analyzers with individual thresholds:

analyzer = Sentimental.new(0.9)
analyzer.get_sentiment('I love your service')
=> :positive
analyzer.get_sentiment('I like your service')
=> :neutral

Constant Summary collapse

@@sentihash =
Hash.new(0.0)
@@threshold =
0.0

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(threshold = nil) ⇒ Sentimental



50
51
52
# File 'lib/sentimental.rb', line 50

def initialize(threshold = nil)
  @threshold = threshold || @@threshold
end

Class Method Details

.load_defaultsObject

Loads the default sentiment files



88
89
90
91
# File 'lib/sentimental.rb', line 88

def self.load_defaults
  load_senti_file(File.dirname(__FILE__) + '/sentiwords.txt')
  load_senti_file(File.dirname(__FILE__) + '/sentislang.txt')
end

.load_senti_file(filename) ⇒ Object

load the specified sentiment file into a hash

filename:string – name of file to load sentihash:hash – hash to load data into return:hash – hash with data loaded



100
101
102
103
104
105
106
107
108
109
110
# File 'lib/sentimental.rb', line 100

def self.load_senti_file(filename)
  # load the word file
  file = File.new(filename)
  while (line = file.gets)
    parsedline = line.chomp.split(/\s/)
    sentiscore = parsedline[0]
    text = parsedline[1]
    @@sentihash[text] = sentiscore.to_f
  end
  file.close
end

.threshold=(threshold) ⇒ Object



112
113
114
# File 'lib/sentimental.rb', line 112

def self.threshold=(threshold)
  @@threshold = threshold
end

Instance Method Details

#get_score(string) ⇒ Object

Function that returns the sentiment value for a given string. This value is the sum of the sentiment values of each of the words. Stop words are NOT removed.

return:float – sentiment value of the current string



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/sentimental.rb', line 61

def get_score(string)
  sentiment_total = 0.0

  #tokenize the string, also throw away some punctuation
  tokens = string.to_s.downcase.split(/[\s\!\?\.]+/)
  
  tokens.each do |token|
    sentiment_total += @@sentihash[token]
  end
  sentiment_total
end

#get_sentiment(string) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/sentimental.rb', line 73

def get_sentiment(string)
  score = get_score(string)

  # if less then the negative threshold classify negative
  if score < (-1 * @threshold)
    :negative
  # if greater then the positive threshold classify positive
  elsif score > @threshold
    :positive
  else
    :neutral
  end
end