基于词典的情感分析方法非常容易被理解,主要利用情感词判断一句话或者一篇文章的情感倾向,下面的程序利用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 words in 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 line in input_file: