Class: SentiWordNet
- Inherits:
-
Object
- Object
- SentiWordNet
- Defined in:
- lib/sentiwordnet_ruby.rb
Constant Summary collapse
- @@sentihash =
{}
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.load_defaults ⇒ Object
63 64 65 |
# File 'lib/sentiwordnet_ruby.rb', line 63 def self.load_defaults load_senti_file(File.dirname(__FILE__) + '/SentiWordNet_3.0.0.txt') end |
.load_senti_file(filename) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'lib/sentiwordnet_ruby.rb', line 67 def self.load_senti_file(filename) word_temp = Hash.new File.readlines(filename).each do |line| data = line.split("\t") score = data[2].to_f - data[3].to_f words = data[4].split(" ") words.each do |w| w_n = w.split("#") w_n[0] += "#"+data[0] index = w_n[1].to_i - 1 if word_temp.has_key?(w_n[0]) v = word_temp[w_n[0]] if (index > v.size) ((v.size)..(index - 1)).each do |i| v << 0.0 end end v[index] = score word_temp[w_n[0]] = v else v = [] (0..(index - 1)).each do |i| v << 0.0 end v[index] = score word_temp[w_n[0]] = v end end end word_temp.keys.each do |k| word = k v = word_temp[k] score = 0.0 sum = 0.0 (0..(v.size - 1)).each do |i| score += (1.0/(i+1).to_f)* v[i] end (1..(v.size)).each do |i| sum += 1.to_f/i.to_f end score /= sum @@sentihash[word] = score end end |
Instance Method Details
#get_score(string) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/sentiwordnet_ruby.rb', line 6 def get_score(string) sentiment_total = 0.0 #tokenize the string, also throw away some punctuation tokens = tokenize(string) tokens.each do |token| if @@sentihash[token+"#n"] sentiment_total += @@sentihash[token+"#n"] end if @@sentihash[token+"#a"] sentiment_total += @@sentihash[token+"#a"] end if @@sentihash[token+"#r"] sentiment_total += @@sentihash[token+"#r"] end if @@sentihash[token+"#v"] sentiment_total += @@sentihash[token+"#v"] end end sentiment_total end |
#get_sentiment(string) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/sentiwordnet_ruby.rb', line 34 def get_sentiment(string) score = get_score(string) if (score > 0.75) return "very_positive" elsif (score > 0.25 && score <= 0.75) return "positive" elsif (score > 0 && score <= 0.25) return "weak_positive" elsif (score == 0) return "neutral" elsif (score < 0 && score >= -0.25) return "weak_negative" elsif (score < -0.25 && score >= -0.75) return "negative" elsif (score < -0.75) return "very_negative" end end |
#tokenize(string) ⇒ Object
54 55 56 57 58 59 60 |
# File 'lib/sentiwordnet_ruby.rb', line 54 def tokenize string fold_case = false string.split(/\s+/).map do |token| stripped = token.gsub(/[^a-zA-Z0-9\']+/, '') fold_case ? stripped.downcase : stripped end end |