? ? ? ?基于詞典的情感分析方法非常容易被理解,主要利用情感詞判斷一句話或者一篇文章的情感傾向,下面的程序利用BosonNLP情感詞典(從https://bosonnlp.com/dev/resource?下載情感詞典)計算情感傾向。在BosonNLP情感詞典中,每個詞有一個情感極性得分。得分大于0,表示為正向情感傾向,得分越高,傾向越強;得分小于0,表示為負向情感傾向,得分越低,傾向越強。
——————————————————————————————————
import re
import jieba# pip install jieba==0.39
class DictBasedSentAnal:
def __init__(self):
self.__root_dir ='dict/'
? ? ? ? self.__sent_dict__ =self.__read_dict(self.__root_dir+'BosonNLP_sentiment_score.txt')
def analyse(self, sentence):
score =0.0
? ? ? ? for wordsin jieba.cut(sentence):
score +=self.__sent_dict__.get(words, 0)
return score
@staticmethod
? ? def __read_dict(path, encoding='utf-8'):
sent_dict = {}
with open(path, encoding=encoding)as input_file:
for linein input_file:
array = re.split('\s+', line.strip())
if len(array) ==2:
sent_dict[array[0]] =float(array[1])
return sent_dict
if __name__ =='__main__':
sentAnal = DictBasedSentAnal()
print('情感得分\t' +'%.2f' % sentAnal.analyse('這個時候反應太慢了!'))
print('情感得分\t' +'%.2f' % sentAnal.analyse('這本書真好,內容特別精彩。'))
——————————————————————————————————
輸出結果:
情感得分 -1.56
情感得分 7.11
——————————————————————————————————
? ? ? ?從上面的例子,可以看出:“這個時候反應太慢了!”判斷為負向情感傾向,“這本書真好,內容特別精彩。”判斷為正向情感傾向,這與我們的認知一致。雖然基于詞典的情感分析方法比較簡單,但是在實際中也證明有價值。以上實現還比較簡答,還有很大的改進空間。