粗淺地突擊學習了一點點自然語言處理,在文章裏會分析python實現的文本情感分析代碼,
代碼功能:分析一句話(中文)裏蘊含的正面情緒和負面情緒並評分,最後返回正負面情緒的總分,平均分,標準差
寫在前面:
其實實現的思路很清晰:分詞 - 詞語分析(正面詞/負面詞/程度詞/否定詞) - 按打分規則評分
|| 導入jieba庫和numpy矩陣
import jieba
import numpy as np
|| 打開詞典文件,返回列表
def open_dict(Dict = 'hahah', path=r'/Users/86133/亂七八糟的代碼們/python/Textming/'):
path = path + '%s.txt' % Dict
dictionary = open(path, 'r', encoding='utf-8')
dict = []
for word in dictionary:
word = word.strip('\n')
dict.append(word)
return dict
|| 將自己的中文語料文本導入(這裏你要修改path路徑)。
deny_word = open_dict(Dict = '否定詞', path= r'/Users/86133/亂七八糟的代碼們/python/Textming/')
posdict = open_dict(Dict = 'positive', path= r'/Users/86133/亂七八糟的代碼們/python/Textming/')
negdict = open_dict(Dict = 'negative', path= r'/Users/86133/亂七八糟的代碼們/python/Textming/')
degree_word = open_dict(Dict = '程度級別詞語', path= r'/Users/86133/亂七八糟的代碼們/python/Textming/'
|| 針對程度詞細分程度:extreme,very,more,ish,last (tips:用以劃分的標誌詞需要在程度詞文本中寫入)
mostdict = degree_word[degree_word.index('extreme')+1 : degree_word.index('very')]#權重4,即在情感詞前乘以4
verydict = degree_word[degree_word.index('very')+1 : degree_word.index('more')]#權重3
moredict = degree_word[degree_word.index('more')+1 : degree_word.index('ish')]#權重2
ishdict = degree_word[degree_word.index('ish')+1 : degree_word.index('last')]#權重0.5
|| 核心代碼:評分邏輯
def judgeodd(num):
if (num % 2) == 0:
return 'even'
else:
return 'odd'
def sentiment_score_list(dataset):
seg_sentence = dataset.split('%%%')
count1 = []
count2 = []
for sen in seg_sentence: #循環遍歷每一個評論
segtmp = jieba.lcut(sen, cut_all=False) #把句子進行分詞,以列表的形式返回
i = 0 #記錄掃描到的詞的位置
a = 0 #記錄情感詞的位置
poscount = 0 #積極詞的第一次分值
poscount2 = 0 #積極詞反轉後的分值
poscount3 = 0 #積極詞的最後分值(包括歎號的分值)
negcount = 0
negcount2 = 0
negcount3 = 0
for word in segtmp:
if word in posdict: # 判斷詞語是否是情感詞
poscount += 1
c = 0
for w in segtmp[a:i]: # 掃描情感詞前的程度詞
if w in mostdict:
poscount *= 4.0
elif w in verydict:
poscount *= 3.0
elif w in moredict:
poscount *= 2.0
elif w in ishdict:
poscount *= 0.5
elif w in deny_word:
c += 1
if judgeodd(c) == 'odd': # 掃描情感詞前的否定詞數
poscount *= -1.0
poscount2 += poscount
poscount = 0
poscount3 = poscount + poscount2 + poscount3
poscount2 = 0
else:
poscount3 = poscount + poscount2 + poscount3
poscount = 0
a = i + 1 # 情感詞的位置變化
elif word in negdict: # 消極情感的分析,與上面一致
negcount += 1
d = 0
for w in segtmp[a:i]:
if w in mostdict:
negcount *= 4.0
elif w in verydict:
negcount *= 3.0
elif w in moredict:
negcount *= 2.0
elif w in ishdict:
negcount *= 0.5
elif w in degree_word:
d += 1
if judgeodd(d) == 'odd':
negcount *= -1.0
negcount2 += negcount
negcount = 0
negcount3 = negcount + negcount2 + negcount3
negcount2 = 0
else:
negcount3 = negcount + negcount2 + negcount3
negcount = 0
a = i + 1
elif word == '!' or word == '!': ##判斷句子是否有感嘆號
for w2 in segtmp[::-1]: # 掃描感嘆號前的情感詞,發現後權值+2,然後退出循環
if w2 in posdict or negdict:
poscount3 += 2
negcount3 += 2
break
i += 1 # 掃描詞位置前移
# 以下是防止出現負數的情況
pos_count = 0
neg_count = 0
if poscount3 < 0 and negcount3 > 0:
neg_count += negcount3 - poscount3
pos_count = 0
elif negcount3 < 0 and poscount3 > 0:
pos_count = poscount3 - negcount3
neg_count = 0
elif poscount3 < 0 and negcount3 < 0:
neg_count = -poscount3
pos_count = -negcount3
else:
pos_count = poscount3
neg_count = negcount3
count1.append([pos_count, neg_count])
count2.append(count1)
count1 = []
return count2
|| 數據彙總
爲每句話創建一個矩陣,矩陣中每行代表一句話按規則劃分出的一系列詞組,每列代表這些詞組的各項打分,
對這些矩陣中的數據進行列求和操作( 即針對一句話的每一個部分的評分進行彙總),最後結果使用一維數組返回
若將需要計算的數據放入二維數組中,將出現TypeError: list indices must be integers or slices, not tuple的報錯因爲在python中列表中的每一個元素大小可能不同,因此不能直接取其某一列進行操作應該利用numpy.array函數將其轉變爲標準矩陣,再對其進行取某一列的操作
def sentiment_score(senti_score_list):
score = []
i = 0
for review in senti_score_list:
i = i + 1
score_array = np.array(review)
Pos = np.sum(score_array[:, 0])
Neg = np.sum(score_array[:, 1])
AvgPos = np.mean(score_array[:, 0])
AvgPos = float('%.1f'%AvgPos)
AvgNeg = np.mean(score_array[:, 1])
AvgNeg = float('%.1f'%AvgNeg)
StdPos = np.std(score_array[:, 0])
StdPos = float('%.1f'%StdPos)
StdNeg = np.std(score_array[:, 1])
StdNeg = float('%.1f'%StdNeg)
score.append([Pos, Neg, AvgPos, AvgNeg, StdPos, StdNeg])
return score
|| 測試代碼
data = """我是真的菜!真的垃圾!"""
data2 = """你是真的強!真的厲害!"""
arr = sentiment_score(sentiment_score_list(data))
for x in range(len(arr)):
print(arr[x])