-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_sentiment.py
More file actions
398 lines (349 loc) · 16.6 KB
/
main_sentiment.py
File metadata and controls
398 lines (349 loc) · 16.6 KB
1
2
3
4
5
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import os
import re
import math
import string
import requests
import json
from itertools import product
from inspect import getsourcefile
B_INCR = 0.293
B_DECR = -0.293
C_INCR = 0.733
N_SCALAR = -0.74
REGEX_REMOVE_PUNCTUATION = re.compile('[%s]' % re.escape(string.punctuation))
PUNC_LIST = [".", "!", "?", ",", ";", ":", "-", "'", "\"",
"!!", "!!!", "??", "???", "?!?", "!?!", "?!?!", "!?!?"]
NEGATE = \
["aint", "arent", "cannot", "cant", "couldnt", "darent", "didnt", "doesnt",
"ain't", "aren't", "can't", "couldn't", "daren't", "didn't", "doesn't",
"dont", "hadnt", "hasnt", "havent", "isnt", "mightnt", "mustnt", "neither",
"don't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't",
"neednt", "needn't", "never", "none", "nope", "nor", "not", "nothing", "nowhere",
"oughtnt", "shant", "shouldnt", "uhuh", "wasnt", "werent",
"oughtn't", "shan't", "shouldn't", "uh-uh", "wasn't", "weren't",
"without", "wont", "wouldnt", "won't", "wouldn't", "rarely", "seldom", "despite"]
BOOSTER_DICT = \
{"absolutely": B_INCR, "amazingly": B_INCR, "awfully": B_INCR, "completely": B_INCR, "considerably": B_INCR,
"decidedly": B_INCR, "deeply": B_INCR, "effing": B_INCR, "enormously": B_INCR,
"entirely": B_INCR, "especially": B_INCR, "exceptionally": B_INCR, "extremely": B_INCR,
"fabulously": B_INCR, "flipping": B_INCR, "flippin": B_INCR,
"fricking": B_INCR, "frickin": B_INCR, "frigging": B_INCR, "friggin": B_INCR, "fully": B_INCR, "fucking": B_INCR,
"greatly": B_INCR, "hella": B_INCR, "highly": B_INCR, "hugely": B_INCR, "incredibly": B_INCR,
"intensely": B_INCR, "majorly": B_INCR, "more": B_INCR, "most": B_INCR, "particularly": B_INCR,
"purely": B_INCR, "quite": B_INCR, "really": B_INCR, "remarkably": B_INCR,
"so": B_INCR, "substantially": B_INCR,
"thoroughly": B_INCR, "totally": B_INCR, "tremendously": B_INCR,
"uber": B_INCR, "unbelievably": B_INCR, "unusually": B_INCR, "utterly": B_INCR,
"very": B_INCR,
"almost": B_DECR, "barely": B_DECR, "hardly": B_DECR, "just enough": B_DECR,
"kind of": B_DECR, "kinda": B_DECR, "kindof": B_DECR, "kind-of": B_DECR,
"less": B_DECR, "little": B_DECR, "marginally": B_DECR, "occasionally": B_DECR, "partly": B_DECR,
"scarcely": B_DECR, "slightly": B_DECR, "somewhat": B_DECR,
"sort of": B_DECR, "sorta": B_DECR, "sortof": B_DECR, "sort-of": B_DECR}
SENTIMENT_LADEN_IDIOMS = {"cut the mustard": 2, "hand to mouth": -2,
"back handed": -2, "blow smoke": -2, "blowing smoke": -2,
"upper hand": 1, "break a leg": 2,
"cooking with gas": 2, "in the black": 2, "in the red": -2,
"on the ball": 2, "under the weather": -2}
SPECIAL_CASE_IDIOMS = {"the shit": 3, "the bomb": 3, "bad ass": 1.5, "yeah right": -2,
"kiss of death": -1.5}
def negated(input_words, include_nt=True):
input_words = [str(w).lower() for w in input_words]
neg_words = []
neg_words.extend(NEGATE)
for word in neg_words:
if word in input_words:
return True
if include_nt:
for word in input_words:
if "n't" in word:
return True
if "least" in input_words:
i = input_words.index("least")
if i > 0 and input_words[i - 1] != "at":
return True
return False
def normalize(score, alpha=15):
norm_score = score / math.sqrt((score * score) + alpha)
if norm_score < -1.0:
return -1.0
elif norm_score > 1.0:
return 1.0
else:
return norm_score
def allcap_differential(words):
is_different = False
allcap_words = 0
for word in words:
if word.isupper():
allcap_words += 1
cap_differential = len(words) - allcap_words
if 0 < cap_differential < len(words):
is_different = True
return is_different
def scalar_inc_dec(word, valence, is_cap_diff):
scalar = 0.0
word_lower = word.lower()
if word_lower in BOOSTER_DICT:
scalar = BOOSTER_DICT[word_lower]
if valence < 0:
scalar *= -1
if word.isupper() and is_cap_diff:
if valence > 0:
scalar += C_INCR
else:
scalar -= C_INCR
return scalar
class SentiText(object):
def __init__(self, text):
if not isinstance(text, str):
text = str(text).encode('utf-8')
self.text = text
self.words_and_emoticons = self._words_and_emoticons()
self.is_cap_diff = allcap_differential(self.words_and_emoticons)
def _words_plus_punc(self):
no_punc_text = REGEX_REMOVE_PUNCTUATION.sub('', self.text)
words_only = no_punc_text.split()
words_only = set(w for w in words_only if len(w) > 1)
punc_before = {''.join(p): p[1] for p in product(PUNC_LIST, words_only)}
punc_after = {''.join(p): p[0] for p in product(words_only, PUNC_LIST)}
words_punc_dict = punc_before
words_punc_dict.update(punc_after)
return words_punc_dict
def _words_and_emoticons(self):
wes = self.text.split()
words_punc_dict = self._words_plus_punc()
wes = [we for we in wes if len(we) > 1]
for i, we in enumerate(wes):
if we in words_punc_dict:
wes[i] = words_punc_dict[we]
return wes
class Sentiments(object):
def __init__(self, lexicon_file="vader_lexicon.txt", emoji_lexicon="emoji_utf8_lexicon.txt"):
_this_module_file_path_ = os.path.abspath(getsourcefile(lambda: 0))
lexicon_full_filepath = os.path.join(os.path.dirname(_this_module_file_path_), lexicon_file)
with open(lexicon_full_filepath, encoding='utf-8') as f:
self.lexicon_full_filepath = f.read()
self.lexicon = self.make_lex_dict()
emoji_full_filepath = os.path.join(os.path.dirname(_this_module_file_path_), emoji_lexicon)
with open(emoji_full_filepath, encoding='utf-8') as f:
self.emoji_full_filepath = f.read()
self.emojis = self.make_emoji_dict()
def make_lex_dict(self):
lex_dict = {}
for line in self.lexicon_full_filepath.split('\n'):
(word, measure) = line.strip().split('\t')[0:2]
lex_dict[word] = float(measure)
return lex_dict
def make_emoji_dict(self):
emoji_dict = {}
for line in self.emoji_full_filepath.split('\n'):
(emoji, description) = line.strip().split('\t')[0:2]
emoji_dict[emoji] = description
return emoji_dict
def review_scores(self, text):
text_token_list = text.split()
text_no_emoji_lst = []
for token in text_token_list:
if token in self.emojis:
description = self.emojis[token]
text_no_emoji_lst.append(description)
else:
text_no_emoji_lst.append(token)
text = " ".join(x for x in text_no_emoji_lst)
sentitext = SentiText(text)
sentiments = []
words_and_emoticons = sentitext.words_and_emoticons
for item in words_and_emoticons:
valence = 0
i = words_and_emoticons.index(item)
if item.lower() in BOOSTER_DICT:
sentiments.append(valence)
continue
if (i < len(words_and_emoticons) - 1 and item.lower() == "kind" and
words_and_emoticons[i + 1].lower() == "of"):
sentiments.append(valence)
continue
sentiments = self.sentiment_valence(valence, sentitext, item, i, sentiments)
sentiments = self._but_check(words_and_emoticons, sentiments)
valence_dict = self.score_valence(sentiments, text)
return valence_dict
def sentiment_valence(self, valence, sentitext, item, i, sentiments):
is_cap_diff = sentitext.is_cap_diff
words_and_emoticons = sentitext.words_and_emoticons
item_lowercase = item.lower()
if item_lowercase in self.lexicon:
valence = self.lexicon[item_lowercase]
if item.isupper() and is_cap_diff:
if valence > 0:
valence += C_INCR
else:
valence -= C_INCR
for start_i in range(0, 3):
if i > start_i and words_and_emoticons[i - (start_i + 1)].lower() not in self.lexicon:
s = scalar_inc_dec(words_and_emoticons[i - (start_i + 1)], valence, is_cap_diff)
if start_i == 1 and s != 0:
s = s * 0.95
if start_i == 2 and s != 0:
s = s * 0.9
valence = valence + s
valence = self._negation_check(valence, words_and_emoticons, start_i, i)
if start_i == 2:
valence = self._special_idioms_check(valence, words_and_emoticons, i)
valence = self._least_check(valence, words_and_emoticons, i)
sentiments.append(valence)
return sentiments
def _least_check(self, valence, words_and_emoticons, i):
if i > 1 and words_and_emoticons[i - 1].lower() not in self.lexicon \
and words_and_emoticons[i - 1].lower() == "least":
if words_and_emoticons[i - 2].lower() != "at" and words_and_emoticons[i - 2].lower() != "very":
valence = valence * N_SCALAR
elif i > 0 and words_and_emoticons[i - 1].lower() not in self.lexicon \
and words_and_emoticons[i - 1].lower() == "least":
valence = valence * N_SCALAR
return valence
@staticmethod
def _but_check(words_and_emoticons, sentiments):
words_and_emoticons_lower = [str(w).lower() for w in words_and_emoticons]
if 'but' in words_and_emoticons_lower:
bi = words_and_emoticons_lower.index('but')
for sentiment in sentiments:
si = sentiments.index(sentiment)
if si < bi:
sentiments.pop(si)
sentiments.insert(si, sentiment * 0.5)
elif si > bi:
sentiments.pop(si)
sentiments.insert(si, sentiment * 1.5)
return sentiments
@staticmethod
def _special_idioms_check(valence, words_and_emoticons, i):
words_and_emoticons_lower = [str(w).lower() for w in words_and_emoticons]
onezero = "{0} {1}".format(words_and_emoticons_lower[i - 1], words_and_emoticons_lower[i])
twoonezero = "{0} {1} {2}".format(words_and_emoticons_lower[i - 2],
words_and_emoticons_lower[i - 1], words_and_emoticons_lower[i])
twoone = "{0} {1}".format(words_and_emoticons_lower[i - 2], words_and_emoticons_lower[i - 1])
threetwoone = "{0} {1} {2}".format(words_and_emoticons_lower[i - 3],
words_and_emoticons_lower[i - 2], words_and_emoticons_lower[i - 1])
threetwo = "{0} {1}".format(words_and_emoticons_lower[i - 3], words_and_emoticons_lower[i - 2])
sequences = [onezero, twoonezero, twoone, threetwoone, threetwo]
for seq in sequences:
if seq in SPECIAL_CASE_IDIOMS:
valence = SPECIAL_CASE_IDIOMS[seq]
break
if len(words_and_emoticons_lower) - 1 > i:
zeroone = "{0} {1}".format(words_and_emoticons_lower[i], words_and_emoticons_lower[i + 1])
if zeroone in SPECIAL_CASE_IDIOMS:
valence = SPECIAL_CASE_IDIOMS[zeroone]
if len(words_and_emoticons_lower) - 1 > i + 1:
zeroonetwo = "{0} {1} {2}".format(words_and_emoticons_lower[i], words_and_emoticons_lower[i + 1],
words_and_emoticons_lower[i + 2])
if zeroonetwo in SPECIAL_CASE_IDIOMS:
valence = SPECIAL_CASE_IDIOMS[zeroonetwo]
n_grams = [threetwoone, threetwo, twoone]
for n_gram in n_grams:
if n_gram in BOOSTER_DICT:
valence = valence + BOOSTER_DICT[n_gram]
return valence
@staticmethod
def _sentiment_laden_idioms_check(valence, senti_text_lower):
idioms_valences = []
for idiom in SENTIMENT_LADEN_IDIOMS:
if idiom in senti_text_lower:
print(idiom, senti_text_lower)
valence = SENTIMENT_LADEN_IDIOMS[idiom]
idioms_valences.append(valence)
if len(idioms_valences) > 0:
valence = sum(idioms_valences) / float(len(idioms_valences))
return valence
@staticmethod
def _negation_check(valence, words_and_emoticons, start_i, i):
words_and_emoticons_lower = [str(w).lower() for w in words_and_emoticons]
if start_i == 0:
if negated([words_and_emoticons_lower[i - (start_i + 1)]]):
valence = valence * N_SCALAR
if start_i == 1:
if words_and_emoticons_lower[i - 2] == "never" and \
(words_and_emoticons_lower[i - 1] == "so" or
words_and_emoticons_lower[i - 1] == "this"):
valence = valence * 1.25
elif words_and_emoticons_lower[i - 2] == "without" and \
words_and_emoticons_lower[i - 1] == "doubt":
valence = valence
elif negated([words_and_emoticons_lower[i - (start_i + 1)]]):
valence = valence * N_SCALAR
if start_i == 2:
if words_and_emoticons_lower[i - 3] == "never" and \
(words_and_emoticons_lower[i - 2] == "so" or words_and_emoticons_lower[i - 2] == "this") or \
(words_and_emoticons_lower[i - 1] == "so" or words_and_emoticons_lower[i - 1] == "this"):
valence = valence * 1.25
elif words_and_emoticons_lower[i - 3] == "without" and \
(words_and_emoticons_lower[i - 2] == "doubt" or words_and_emoticons_lower[i - 1] == "doubt"):
valence = valence
elif negated([words_and_emoticons_lower[i - (start_i + 1)]]):
valence = valence * N_SCALAR
return valence
def _punctuation_emphasis(self, text):
ep_amplifier = self._amplify_ep(text)
qm_amplifier = self._amplify_qm(text)
punct_emph_amplifier = ep_amplifier + qm_amplifier
return punct_emph_amplifier
@staticmethod
def _amplify_ep(text):
ep_count = text.count("!")
if ep_count > 4:
ep_count = 4
ep_amplifier = ep_count * 0.292
return ep_amplifier
@staticmethod
def _amplify_qm(text):
qm_count = text.count("?")
qm_amplifier = 0
if qm_count > 1:
if qm_count <= 3:
qm_amplifier = qm_count * 0.18
else:
qm_amplifier = 0.96
return qm_amplifier
@staticmethod
def _sift_sentiment_scores(sentiments):
pos_sum = 0.0
neg_sum = 0.0
neu_count = 0
for sentiment_score in sentiments:
if sentiment_score > 0:
pos_sum += (float(sentiment_score) + 1)
if sentiment_score < 0:
neg_sum += (float(sentiment_score) - 1)
if sentiment_score == 0:
neu_count += 1
return pos_sum, neg_sum, neu_count
def score_valence(self, sentiments, text):
if sentiments:
sum_s = float(sum(sentiments))
punct_emph_amplifier = self._punctuation_emphasis(text)
if sum_s > 0:
sum_s += punct_emph_amplifier
elif sum_s < 0:
sum_s -= punct_emph_amplifier
compound = normalize(sum_s)
pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)
if pos_sum > math.fabs(neg_sum):
pos_sum += punct_emph_amplifier
elif pos_sum < math.fabs(neg_sum):
neg_sum -= punct_emph_amplifier
total = pos_sum + math.fabs(neg_sum) + neu_count
pos = math.fabs(pos_sum / total)
neg = math.fabs(neg_sum / total)
neu = math.fabs(neu_count / total)
else:
compound = 0.0
pos = 0.0
neg = 0.0
neu = 0.0
sentiment_dict = \
{"neg": round(neg, 3),
"neu": round(neu, 3),
"pos": round(pos, 3),
"compound": round(compound, 4)}
return sentiment_dict