forked from EKT1/valence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
valencecolor.py
370 lines (312 loc) · 9.04 KB
/
valencecolor.py
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
# -*- coding: utf-8 -*-
import sys
import array
import codecs
import re
from optparse import OptionParser
import bayes
#translation
try:
from ekorpus.lib.base import *
except ImportError:
def _(s):
return s
silent = None
hybrid = 1
htmlStart = """
<html><head>
<style>
</style>
</head>
<body>
"""
htmlEnd = """
</body>
</html>
"""
paraOpen = '<div class="'
paraClose = '</div>'
words = ''
def load():
global words
if words:
return words
words = {}
with codecs.open('sqnad.csv', 'r', encoding='utf-8') as f:
for row in f:
parts=row.split(',',3)
if len(parts)<2:
continue
words[parts[0]] = parts[1]
words['ei'] = ''
words['ega'] = ''
return words
def mark(text, words):
space = re.compile('([\'".,!?\\s\\(\\)]+)')
stop = re.compile("[,.!?]")
para = re.compile("\\n")
textWords = space.split(text)
positive = negative = extreme = count = 0
total = [0,0,0,0]
paraStart=0
r = []
stats = []
bayesStats = []
wordStyle = { '1':'word positiveW', '-1':'word negativeW', '-8':'word extremeW'}
statStyle = { 'positiivne':'positiveB', 'negatiivne':'negativeB', 'neutraalne':'neutralB' }
statWords = []
def doBayes():
feats = dict([(item, True) for item in statWords if not space.match(item)])
cs = bayes.prob_classify(feats)
bayesStats.append(cs)
return statStyle[cs.max()]
def closePara():
if len(r) != paraStart:
s = '<a name="%d"></a>%s' % (len(stats), paraOpen)
if extreme > 0:
s = s+'para extremeP'
elif positive>negative:
s = s+'para positiveP'
elif negative>positive:
s = s+'para negativeP'
elif positive>0:
s = s+'para mixedP'
else:
s = s+'para neutralP'
if hybrid:
stat_class = doBayes()
s = s + " " + stat_class
del statWords[:]
s = s + '">'
r.insert(paraStart,s)
r.append(word)
r.append(paraClose)
total[0] = total[0] + count
total[1] = total[1] + positive
total[2] = total[2] + negative
total[3] = total[3] + extreme
stats.append((count,positive,negative,extreme))
return len(r)
try:
i = iter(textWords)
while 1:
word = next(i)
if not word:
continue
if para.search(word):
paraStart=closePara()
positive = negative = extreme = count = 0
continue
if not space.search(word):
count = count + 1
if hybrid:
statWords.append(word)
w = word.lower()
if w in words:
flag = words[w]
if not flag: #negator
separator = next(i,'.')
word = word + separator
if stop.search(separator): # neg eos
r.append(word)
continue
word2 = next(i,'')
if not word2: # neg eof
r.append(word)
continue
word = word + word2
w = word2.lower()
if w in words:
flag = words[w]
if flag == "1":
flag = "-1"
elif flag == "-1":
flag = "1"
elif flag == "-8":
flag = "-8"
else:
flag = '' # neg neg
else:
flag = "-1"
if flag == "1":
positive = positive + 1
elif flag == "-1":
negative = negative + 1
elif flag == "-8":
extreme = extreme + 1
if flag:
r.append('<span class="%s">' % (wordStyle[flag]))
r.append(word)
if flag:
r.append("</span>")
else:
r.append(word)
word=''
except StopIteration:
pass
closePara()
rtn = '<div class="text">' + ''.join(r) + '</div>'
# rtn: html
# total: word counts (count, positive, negative, extreme) for whole text
# stats: list of word counts for each paragraph
# bayesStats: prob distribution for each paragraph
return (rtn, total, stats, bayesStats)
def textValence(all,para):
"""Calculate whole text emotion from paragraphs words counts.
where para = [neutral, positive, negative, mixed] total number of words in each type of paragraph.
and "all" is the total number of words in the text.
"""
count=0 # number of different emotions
maxVal=pos=0 # max and its position
for i, val in enumerate(para):
if val>0:
count = count+1
if val>maxVal:
maxVal=val
pos=i
valence = _('mostly mixed')
if count==1:
valence = [_('only neutral'), _('only positive'), _('only negative'), _('only mixed')][pos]
elif count==2:
if (float(all)/maxVal)<1.5:
valence = [_('mostly neutral'), _('mostly positive'), _('mostly negative'), _('mostly mixed')][pos]
else:
if (all/maxVal)<=1:
valence = [_('mostly neutral'), _('mostly positive'), _('mostly negative'), _('mostly mixed')][pos]
return valence
classifier2style = { 'positiivne':'tile positiveT','negatiivne':'tile negativeT','neutraalne':'tile neutralT'}
def chartStats(total, stats, bayesStats):
""" Create the bar for the statistical estimate
"""
all = total[0]
if all==0:
return ''
r = []
r.append('<div class="chart">')
i = 0
for s in stats:
prob = bayesStats[i]
classifier = prob.max()
valence = classifier2style[classifier]
label1=_('positive =')
label2=_('negative =')
label3=_('neutral =')
r.append(
'''<a href="#%d"><div class="bar %s" style="width:%.2f%%"> <span class="info">%s %d<br/>%s:<br/> %s %.2f<br/> %s %.2f<br/> %s %.2f</span></div></a>'''
% (i,valence,(10000*s[0]/all)/100.0,_('words:'),s[0],_("Probability"),label1,prob.prob('positiivne'),label2,prob.prob('negatiivne'),label3,prob.prob('neutraalne')))
i = i+1
r.append('</div>')
# html bar of paragraph properties
return ("".join(r))
def chart(total, stats):
""" Create the bar for lexicon based estimation
"""
all = total[0]
if all==0:
return ''
r = []
para = [0,0,0,0] # neutral, positive, negative, mixed
r.append('<div class="chart">')
i = 0
for s in stats:
positive = s[1]
negative = s[2]
extreme = s[3]
valence = 'tile neutralT'
if extreme>0:
para[2]=para[2]+s[0] #count all words in this paragraph as negative
valence = 'tile extremeT'
elif positive>negative:
para[1]=para[1]+s[0]
valence = 'tile positiveT'
elif negative>positive:
para[2]=para[2]+s[0]
valence = 'tile negativeT'
elif positive>0:
para[3]=para[3]+s[0]
valence = 'tile mixedT'
else:
para[0]=para[0]+s[0]
label1=_('positive:')
label2=_('negative:')
label3=_('extreme:')
r.append(
'''
<a href="#%d"><div class="bar %s" style="width:%.2f%%"> <span class="info">%s %d<br/>%s %d<br/>%s %d<br/>%s %d</span></div></a>'''
% (i, valence, (10000*s[0]/all)/100.0, _('words:'), s[0], label1, positive, label2, negative, label3, extreme)
)
i = i+1
r.append('</div>')
valence = textValence(all,para)
#valence: text valence name
#html: html bar of paragraph properties
return (valence, formatValence(valence) + ("".join(r)))
#<div class="bar" style="width:10%;height:90%;top:10%;background-color:blue"> </div>
def formatValence(valence) :
return '<div class="textvalence">%s: %s</div>' % (_('Valence'),valence)
def marktext(text, dataonly, lexiconbased) :
"""For web"""
global words
load()
t = mark(text, words)
s = chart(t[1],t[2])
if dataonly:
if dataonly=="2":
return s[0]
if dataonly=="3":
return emotionBayes(t[3],t[1],t[2])
return s[1] + t[0]
if not lexiconbased:
return t[0] + formatValence(emotionBayes(t[3],t[1],t[2]))+chartStats(t[1],t[2],t[3])
return t[0] + s[1]
# for c in cs.samples():
# print c, cs.prob(c)
def emotionBayes(emotions, total, stats):
all = total[0]
if all==0:
return ''
para = [0,0,0,0] # neutral, positive, negative, mixed
for i,es in enumerate(emotions):
e = es.max()
n = stats[i][0]
if e=="positiivne":
para[1] = para[1]+n
elif e=="negatiivne":
para[2] = para[2]+n
elif e=="neutraalne":
para[0] = para[0]+n
return textValence(all,para)
def doit(filename):
"""Standalone"""
global words
load()
fi = codecs.open(filename, 'r', encoding='utf-8')
text=fi.read()
fi.close()
t = mark(text,words)
s = chart(t[1],t[2])
if not silent:
fo = codecs.open(filename+'.html', 'w', encoding='utf-8')
fo.write(htmlStart)
fo.write(t[0])
#fo.write(t[0].replace('\r','<br>'))
fo.write(chartStats(t[1],t[2],t[3]))
fo.write(htmlEnd)
fo.close()
else:
print "Dict:", s[0]
print "Dict:", s[1]
print "Bayes:", emotionBayes(t[3],t[1],t[2]), t[3]
def main():
global silent
parser = OptionParser(usage='Usage: %prog file')
parser.add_option('-s', '--silent', action="store_true", dest="silent", help='Silent: no html file')
opts, args = parser.parse_args()
if len(args)!=1: # or not opts.segment:
parser.print_help()
sys.exit(1)
if opts.silent:
silent=opts.silent
doit(args[0])
if __name__ == '__main__':
main()