基于词典的情感分析方法非常容易被理解,主要利用情感词判断一句话或者一篇文章的情感倾向,下面的程序利用BosonNLP情感词典(从/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:
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
从上面的例子,可以看出:“这个时候反应太慢了!”判断为负向情感倾向,“这本书真好,内容特别精彩。”判断为正向情感倾向,这与我们的认知一致。虽然基于词典的情感分析方法比较简单,但是在实际中也证明有价值。以上实现还比较简答,还有很大的改进空间。
来源: