基于情感词典的文本情感分析(一个最简单的举例能直接运行)

    技术2022-07-13  67

    1. 使用情感词典进行情感分析的思路为

    1) 将Web文本进行分句,使其以句子为单位进行处理; 2) 从分句中抽取连词和否定词,并标记相应连词与否定词位置; 3) 访问情感词汇本体,确定词汇极性及其强度; 4) 针对连词(若有),通过连词连词位置,确定前句与后句所占比重,针对否定词(若有),根据否定词位置判断双重否定,以及临近词汇的极性反转;若不包含连词或者否定词,则略过该步骤; 5) 累加本句情感计算评分;

    2. 第一次学习情感词典进行情感分析,也是根据下面这个博主链接进行修改的,主要改善了几个功能:

    原链接为:https://blog.csdn.net/Petrichoryi/article/details/105861462?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase 这篇博主过程写得很详细,若果有什么细节问题可以直接参考这篇博主的内容。

    a)第一个情感词前面的程度词或者否定词,原文并没有考虑。 b)在两个情感词之间否定词的用法稍微进行了一点改变。

    代码测试部分(可以直接复制运行)

    因为要测试代码的正确性,所以直接拿一个简单的例子进行代码的测试(可以直接运行),后序会读取文本数据和词典数据进行测试。每个情感词,修饰词和程度副词的权重都是我人为设置的权重 只是为了检验正确性。

    import jieba from collections import defaultdict a='今天天气很好,但是我非常不喜欢,不开心' c=[] b=jieba.cut(a) for i in b: print(i) c.append(i) adj = {'好':'1','喜欢':'2','开心':'3'}#形容词 degree = {'很':'2','非常':'2.0'}#程度词 notword ={'不':'-2.0','非':'-1.0'} #否定词 adv = {'但是':'1.2'}#转折词 d=[] score=int(0) for i in c: if i in adj.keys() or i in notword.keys() or i in degree.keys() or i in adv.keys(): d.append(i) print(d) sen_word = dict() not_word = dict() degree_word = dict() for i in range(len(d)): word = d[i] if word in adj.keys() and word not in degree.keys() and word not in notword.keys(): # 找出分词结果中在情感字典中的词 sen_word[i] = adj[word] elif word in notword.keys() and word not in degree.keys(): # 分词结果中在否定词列表中的词 not_word[i] = notword[word] elif word in degree.keys(): # 分词结果中在程度副词中的词 degree_word[i] = degree[word] w= 1.0 score = 0 print(sen_word) print(not_word) print(degree_word) #情感词下标初始化 sentiment_index = -1 sentiment_index_list =list(sen_word.keys()) #对第一个情感词前的程度副词或者否定词进行得分处理 #print(sentiment_index_list) for j in range(0,sentiment_index_list[0]): if j in not_word.keys(): w=w*float(not_word[j]) elif j in degree_word.keys(): w=w*float(degree_word[j]) #遍历分词结果 print(len(d)) for i in range(0,len(d)): #如果是情感词 if i in sen_word.keys(): print(i) score =score + w*float(sen_word[i]) print('分数',score) #w一定要初始化一下 每个W只跟你所对应的情感词有关系 w=1.0 #情感词下标加1,获取下一个情感词的位置 sentiment_index += 1 if sentiment_index< len(sentiment_index_list)-1: #判断当前的情感词与下一个情感词之间是否有程度副词或否定词 for j in range(sentiment_index_list[sentiment_index],sentiment_index_list[sentiment_index+1]): #更新权重,如果有否定词,权重取反 if j in not_word.keys(): w=w*float(not_word[j]) elif j in degree_word.keys(): w=w*float(degree_word[j]) #定位到下一个情感词 if sentiment_index < len(sentiment_index_list)-1: i = sentiment_index_list[sentiment_index+1] print(score)

    比如本句话的情感得分应该为:很好+非常不喜欢+不*开心:2X1+2X(-2)X2+(-2.)X3=-12

    运行的结果为:

    这个代码块中并没有对程度词,情感词和否定词的词典进行读取以及文档的读取。只是举一个具体的例子方便理解。或许会对这些进行整理并且针对中文语法分析中的转折词或者加强语气的标点符号进行更深一步的研究。

    Processed: 0.015, SQL: 9