-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
732 lines (456 loc) · 14.4 KB
/
test.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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# encoding=utf-8
'''
Created on 2015年12月10日
@author: nali
'''
import csv
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import BernoulliNB
from sklearn import cross_validation
from sklearn.metrics import classification_report
import numpy as np
from sklearn.metrics import accuracy_score
import jieba
import jieba.posseg as pseg
from xml.dom import minidom
import MySQLdb
import re
import random
conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="cy1993",port=3306,db="lexicon",charset='utf8')
cur=conn.cursor()
#query="insert into lex(word,polar) values(%s,%s)"
#str="看了这本书,总体感觉老外带孩子比中国人要粗些。其实,本来就不用太过细致了,人家那样照样能把孩子带好,不能把孩子放在保险箱里养。这书挺好的,可以看看"
#cuts=pseg.cut(str)
InverseWord_dict={}
stopWord_dict={}
sentiment_dict={}
level_dict={}
def build_sentiment_dict():
global sentiment_dict
query2="select * from sentiment"
cur.execute(query2)
data=cur.fetchall()
for s in data:
sentiment_dict[s[1]]=s[2]
print len(sentiment_dict.keys())
def getPolar(word):
global sentiment_dict
if sentiment_dict.has_key(word):
return sentiment_dict[word]
else:
return -1
"""
query2="select polar from sentiment where word = %s"
cur.execute(query2,(word))
polar=cur.fetchone()
if polar is not None:
#print polar
return polar[0]
else :
return -1
"""
def build_level_dict():
global level_dict
query2="select * from level"
cur.execute(query2)
data=cur.fetchall()
for s in data:
level_dict[s[1]]=(s[2],s[3])
print len(level_dict.keys())
def getLevel(word):
global level_dict
if level_dict.has_key(word):
return level_dict[word]
else:
return (-1,-1000.0)
"""
query2="select * from level where word = %s"
cur.execute(query2,(word))
res=cur.fetchone()
if res is not None:
#print float(res[3])
return (res[2],float(res[3]) )
else :
return (-1,-1000.0)
"""
def getSimilar(word):
query2 = "select * from similar where word = %s"
query3 = "select * from similar where class = %s"
cur.execute(query2, (word))
tmp = cur.fetchone()
data = []
if tmp is not None:
word_class = tmp[2]
#print word_class
cur.execute(query3, (word_class))
sim = cur.fetchall()
if sim is not None:
for s in sim:
data.append(s[1])
return data
def build_InverseWord_dict():
global InverseWord_dict
query2="select * from inverse"
cur.execute(query2)
data=cur.fetchall()
for s in data:
InverseWord_dict[s[0]]=1
print len(InverseWord_dict.keys())
#判断一个词语是不是否定词
def isInverseWord(word):
global InverseWord_dict
if InverseWord_dict.has_key(word):
return 1
else:
return -1
"""
query2="select * from inverse where word = %s"
cur.execute(query2,(word))
res=cur.fetchone()
if res is not None:
#print polar
return 1
else :
return -1
"""
def build_stopWord_dict():
global stopWord_dict
query2="select * from stop"
cur.execute(query2)
data=cur.fetchall()
for s in data:
stopWord_dict[s[0]]=1
print len(stopWord_dict.keys())
def isstopWord(word):
global stopWord_dict
if stopWord_dict.has_key(word):
return 1
else:
return -1
"""
query2="select * from stop where word = %s"
cur.execute(query2,(word))
res=cur.fetchone()
if res is not None:
#print polar
return 1
else :
return -1
"""
##===========================================================
def insert_stop(word):
query="insert into stop(word) values(%s)"
try:
cur.execute(query,(word ) )
conn.commit()
except:
print "insert fail-->"+word
#加载停用词
def load_stop():
file_name="dict/stopword.txt"
file=open(file_name,"r")
lines=file.readlines()
for l in lines:
insert_stop(l.strip())
def insert_similar(word,word_class):
query3="insert into similar(word,class) values(%s,%s)"
try:
cur.execute(query3,(word,word_class))
conn.commit()
except:
print "insert fail"
#加载同义词
def load_similar():
file_name="dict/similarWord.txt"
file=open(file_name,"r")
lines=file.readlines()
for l in lines:
words=l.split(' ')
word_class=words[0]
for i in range(1,len(words)):
w=words[i]
print w
insert_similar(w.strip(),word_class.strip())
print "load_similar finish"
def insert_level(word,word_class,score):
query4="insert into level(word,class,score) values(%s,%s,%s)"
try:
cur.execute(query4,(word,word_class,score))
conn.commit()
except:
print "insert fail"
def load_level_sub(file_name,word_class,score):
file=open(file_name,"r")
lines=file.readlines()
for l in lines:
w=l.strip()
print w
print word_class
print score
insert_level(w,word_class,score)
print file_name+" load_level finish"
file.close()
#加载程度副词
def load_level():
most="dict/most.txt"
most_score=6.5
load_level_sub(most,1,most_score)
very="dict/very.txt"
very_score=4.5
load_level_sub(very,2,very_score)
more="dict/more.txt"
more_score=2.5
load_level_sub(more,3,more_score)
ish="dict/ish.txt"
ish_score=1.5
load_level_sub(ish,4,ish_score)
insufficiently="dict/insufficiently.txt"
insufficiently_score=0.75
load_level_sub(insufficiently,5,insufficiently_score)
#over="dict/over.txt"
#over_score=0.05
#load_level_sub(over,6,over_score)
def insert_inverse(word):
query="insert into inverse(word) values(%s)"
try:
cur.execute(query,(word ) )
conn.commit()
except:
print "insert fail-->"+word
#加载否定词
def load_inverse():
file_name="dict/inverse.txt"
file=open(file_name,"r")
lines=file.readlines()
for l in lines:
insert_inverse(l.strip())
def insert_sentiment(word,polar):
query="insert into sentiment(word,polar) values(%s,%s)"
try:
cur.execute(query,(word,polar))
conn.commit()
except:
print "insert fail->>"+word
# 0代表中性,1代表褒义,2代表贬义,3代表兼有褒贬两性。
def load_sentiment():
neg_file = "dict/negtive.txt"
pos_file = "dict/postive.txt"
fileneg = open(neg_file, "r")
lines_neg = fileneg.readlines()
for l in lines_neg:
w = l.strip()
if w != "" and w !=" ":
insert_sentiment(w, 2)
# ws=getSimilar(w)
# for wss in ws:
# insert_sentiment(wss,2)
########################
filepos = open(pos_file, "r")
lines_pos = filepos.readlines()
for l in lines_pos:
w = l.strip()
if w != "" and w !=" ":
insert_sentiment(w, 1)
# ws=getSimilar(w)
# for wss in ws:
# insert_sentiment(wss,1)
"""
print "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"
raw_input("sssssssss")
#======insert similar ==================
for l in lines_neg:
w=l.strip()
ws=getSimilar(w)
for wss in ws:
insert_sentiment(wss,2)
########################
for l in lines_pos:
w=l.strip()
ws=getSimilar(w)
for wss in ws:
insert_sentiment(wss,1)
"""
def judgePolar(text):
tokens=pseg.cut(text)
words=[]
flag=[]
polars=["","postive","negtive"]
levels=["","most","more","very","little","insufficiently"]
sss=""
for w,pos in tokens:
#print w
words.append(w)
stop=isstopWord(w)
if 1==stop:
flag.append(("none",""))
continue
inv=isInverseWord(w)
level,lev_score=getLevel(w)
if 1 == inv:
flag.append(("inverse",""))
continue
#print ("%s----->[inverse]"%(w))
elif -1 != level:
flag.append(("level",levels[level]))
continue
else:
polar=getPolar(w)
if polar != -1:
flag.append(("sentiment",polars[polar]))
#print ("%s----->[sentiment]%s"%(w,polars[polar]))
else:
flag.append(("none",""))
#print ("%s----->[none]"%(w))
pos_score=0.0
neg_score=0.0
inv_cont=0
lev_cont=0
for i in range(len(flag)):
if flag[i][0] == "sentiment":
#postive
sss = sss + "-" + words[i] + "[" + flag[i][1] + "]"
tmp_score = 1.0
# 往前找程度副词
for k in range(i - 1, -1, -1):
if flag[k][0] == "sentiment":
break
elif flag[k][0] == "level":
level,lev_score= getLevel(words[k])
tmp_score = tmp_score * lev_score
break
#往前计算否定词的数量
tmp_inv_cnt=0
for k in range(i - 1, -1, -1):
if flag[k][0] == "sentiment":
break
elif flag[k][0] == "inverse":
tmp_inv_cnt+=1
if flag[i][1]==polars[1]:
if tmp_inv_cnt%2 != 0 :
neg_score+=tmp_score
else:
pos_score+=tmp_score
else:
if tmp_inv_cnt%2 != 0 :
pos_score+=tmp_score
else:
neg_score+=tmp_score
elif flag[i][0] == "inverse":
sss = sss + "-" +words[i] + "[" + flag[i][0] + "]"
inv_cont = inv_cont + 1
elif flag[i][0] == "level":
lev_cont+=1
sss = sss + "-" + words[i] + "[" + flag[i][0] + "]"
else:
sss = sss + "-" + words[i]
#print ("pos_score=%f"%(pos_score))
#print ("neg_score=%f"%(neg_score))
#print sss
pola=0
#sum=pos_score+neg_score
if pos_score<=0.000000001 and neg_score<=0.00000001:
if inv_cont%2!=0:
pola=2
return (pola,0.0,0.5,sss)
elif inv_cont!=0:
pola=1
return (pola,0.5,0.0,sss)
else:
if lev_cont !=0:
return (1,0.2,0.0,sss)
else:
return (0,0.0,0.0,sss)
elif pos_score < neg_score:
pola=2
elif pos_score > neg_score:
pola=1
else:
if inv_cont%2!=0:
pola=2
return (pola,pos_score,neg_score,sss)
elif inv_cont!=0:
pola=1
return (pola,pos_score,neg_score,sss)
else:
if lev_cont !=0:
return (1,pos_score+0.25,neg_score,sss)
else:
return (0,pos_score,neg_score,sss)
#print ("polar=%s"%(polars[pola]))
return (pola,pos_score,neg_score,sss)
def process_text(text):
sp=',|,|。|\?|!|~|;|;|\n'
texts=re.split(sp, text)
ret=[]
for line in texts:
w=line.strip()
if w =="" :
pass
#print "null -->"+line
else:
t=judgePolar(w)
print ("%s===>%d %f %f "%(t[3],t[0],t[1],t[2]))
ret.append(t)
return ret
def calculate_score(data):
pos=0.0
neg=0.0
cnt=len(data)
pos_cnt=0
neg_cnt=0
for k in data:
if k[0] !=0:
pos+=k[1]
neg+=k[2]
if k[0]==1:
pos_cnt+=1
elif k[0]==2:
neg_cnt+=1
if pos>neg:
return 1
elif pos<neg:
return -1
else:
if pos_cnt>neg_cnt:
return 1
elif pos_cnt<neg_cnt:
return -1
else:
return random.randint(0,1)-1
def allJudge(data_train,target_train):
ret=[]
cnt=0
for i in range(len(data_train)):
print ("%d================================================="%cnt)
text=data_train[i]
label=target_train[i]
arr=process_text(text)
result=calculate_score(arr)
if result ==1:
if label == "negative" :
print (">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>error---suppose negative but positive-------%d"%cnt)
ret.append("positive")
else:
if label == "positive" :
print (">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>error---suppose positive but negative-------%d"%cnt)
ret.append("negative")
cnt+=1
return ret
"""
#@@@@@@@@@@@@@@@@@@
load_similar()
load_level()
load_inverse()
load_sentiment()
load_stop()
#@@@@@@@@@@@@@@@@@@@@
"""
print "build_sentiment_dict"
build_sentiment_dict()
print "build_level_dict"
build_level_dict()
print "build_InverseWord_dict"
build_InverseWord_dict()
print "build_stopWord_dict"
build_stopWord_dict()