首先对单条微博进行文本预处理,并以标点符号为分割标志,将单条微博分割为n个句子,提取每个句子中的情感词。以下两步的处理均以分句为处理单位。

第二步在情感词表中寻找情感词,以每个情感词为基准,向前依次寻找程度副词,否定词,并作相应分值计算。随后对分句中每个情感词的得分作求和运算。

第三步判断该句是否为感叹句,是否为反问句,以及是否存在表情符号。如果是,则分句在原有分值的基础上加上或减去对应的权值。

最后对该条微博的所有分句的分值进行累加,获得该条微博的最终得分。

程序文件分布:

代码1:

# -*- coding: utf-8 -*-
import jieba
import jieba.posseg as pseg
print ("加载用户词典...")
jieba.load_userdict('C:/Anaconda3/Lib/site-packages/jieba/pos_dict.txt')
jieba.load_userdict('C:/Anaconda3/Lib/site-packages/jieba/neg_dict.txt')# 分词,返回List
def segmentation(sentence):seg_list = jieba.cut(sentence)seg_result = []for w in seg_list:seg_result.append(w)print(seg_result[:])return seg_result# 分词,词性标注,词和词性构成一个元组
def postagger(sentence):pos_data = pseg.cut(sentence)pos_list = []for w in pos_data:pos_list.append((w.word, w.flag))#print pos_list[:]return pos_list# 句子切分
def cut_sentence(words):words = words.encode('utf8').decode('utf8')start = 0i = 0token = 'meaningless'sents = []punt_list = ',.!?;~。!?;~… '.encode('utf8').decode('utf8')# print("punc_list", punt_list)for word in words:# print("word", word)if word not in punt_list:   # 如果不是标点符号# print("word1", word)i += 1token = list(words[start:i+2]).pop()# print("token:", token)elif word in punt_list and token in punt_list:  # 处理省略号# print("word2", word)i += 1token = list(words[start:i+2]).pop()# print("token:", token)else:# print("word3", word)sents.append(words[start:i+1])   # 断句start = i + 1i += 1if start < len(words):   # 处理最后的部分sents.append(words[start:])# print(words[start:])return sentsdef read_lines(filename):fp = open(filename, 'rb')lines = []for line in fp.readlines():line = line.strip()line = line.decode("utf8")lines.append(line)fp.close()return lines# 去除停用词
def del_stopwords(seg_sent):stopwords = read_lines("D://untitled/Sentiment_dict/emotion_dict/stop_words.txt")  # 读取停用词表new_sent = []   # 去除停用词后的句子for word in seg_sent:if word in stopwords:continueelse:new_sent.append(word)return new_sent# 获取六种权值的词,根据要求返回list,这个函数是为了配合Django的views下的函数使用
def read_quanzhi(request):result_dict = []if request == "one":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/most.txt")elif request == "two":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/very.txt")elif request == "three":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/more.txt")elif request == "four":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/ish.txt")elif request == "five":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/insufficiently.txt")elif request == "six":result_dict = read_lines("D://untitled/Sentiment_dict/degree_dict/inverse.txt")else:passreturn result_dict

代码2:

# -*- coding: utf-8 -*-
import text_process as tp
import numpy as np
# 1.读取情感词典和待处理文件
# 情感词典
print ("reading...")
posdict = tp.read_lines("D://untitled/Sentiment_dict/emotion_dict/pos_all_dict.txt")
negdict = tp.read_lines("D://untitled/Sentiment_dict/emotion_dict/neg_all_dict.txt")
# 程度副词词典
mostdict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/most.txt')   # 权值为2
verydict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/very.txt')   # 权值为1.5
moredict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/more.txt')   # 权值为1.25
ishdict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/ish.txt')   # 权值为0.5
insufficientdict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/insufficiently.txt')  # 权值为0.25
inversedict = tp.read_lines('D://untitled/Sentiment_dict/degree_dict/inverse.txt')  # 权值为-1# 情感级别
emotion_level1 = "悲伤。在这个级别的人过的是八辈子都懊丧和消沉的生活。这种生活充满了对过去的懊悔、自责和悲恸。在悲伤中的人,看这个世界都是灰黑色的。"
emotion_level2 = "愤怒。如果有人能跳出冷漠和内疚的怪圈,并摆脱恐惧的控制,他就开始有欲望了,而欲望则带来挫折感,接着引发愤怒。愤怒常常表现为怨恨和复仇心里,它是易变且危险的。愤怒来自未能满足的欲望,来自比之更低的能量级。挫败感来自于放大了欲望的重要性。愤怒很容易就导致憎恨,这会逐渐侵蚀一个人的心灵。"
emotion_level3 = "淡定。到达这个能级的能量都变得很活跃了。淡定的能级则是灵活和无分别性的看待现实中的问题。到来这个能级,意味着对结果的超然,一个人不会再经验挫败和恐惧。这是一个有安全感的能级。到来这个能级的人们,都是很容易与之相处的,而且让人感到温馨可靠,这样的人总是镇定从容。他们不会去强迫别人做什么。"
emotion_level4 = "平和。他感觉到所有的一切都生机勃勃并光芒四射,虽然在其他人眼里这个世界还是老样子,但是在这人眼里世界却是一个。所以头脑保持长久的沉默,不再分析判断。观察者和被观察者成为同一个人,观照者消融在观照中,成为观照本身。"
emotion_level5 = "喜悦。当爱变得越来越无限的时候,它开始发展成为内在的喜悦。这是在每一个当下,从内在而非外在升起的喜悦。这个能级的人的特点是,他们具有巨大的耐性,以及对一再显现的困境具有持久的乐观态度,以及慈悲。同时发生着。在他们开来是稀松平常的作为,却会被平常人当成是奇迹来看待。"
# 情感波动级别
emotion_level6 = "情感波动很小,个人情感是不易改变的、经得起考验的。能够理性的看待周围的人和事。"
emotion_level7 = "情感波动较大,周围的喜悦或者悲伤都能轻易的感染他,他对周围的事物有敏感的认知。"# 2.程度副词处理,根据程度副词的种类不同乘以不同的权值
def match(word, sentiment_value):if word in mostdict:sentiment_value *= 2.0elif word in verydict:sentiment_value *= 1.75elif word in moredict:sentiment_value *= 1.5elif word in ishdict:sentiment_value *= 1.2elif word in insufficientdict:sentiment_value *= 0.5elif word in inversedict:sentiment_value *= -1return sentiment_value# 3.情感得分的最后处理,防止出现负数
# Example: [5, -2] →  [7, 0]; [-4, 8] →  [0, 12]
def transform_to_positive_num(poscount, negcount):pos_count = 0neg_count = 0if poscount < 0 and negcount >= 0:neg_count += negcount - poscountpos_count = 0elif negcount < 0 and poscount >= 0:pos_count = poscount - negcountneg_count = 0elif poscount < 0 and negcount < 0:neg_count = -poscountpos_count = -negcountelse:pos_count = poscountneg_count = negcountreturn (pos_count, neg_count)# 求单条文章语句的情感倾向总得分
def single_review_sentiment_score(weibo_sent):single_review_senti_score = [] # 定义一个空列表cuted_review = tp.cut_sentence(weibo_sent)  # 句子切分,单独对每个句子进行分析for sent in cuted_review: # 遍历分句seg_sent = tp.segmentation(sent)   # 分词seg_sent = tp.del_stopwords(seg_sent)[:]i = 0    # 记录扫描到的词的位置s = 0    # 记录情感词的位置poscount = 0    # 记录该分句中的积极情感得分negcount = 0    # 记录该分句中的消极情感得分for word in seg_sent:   # 逐词分析if word in posdict:  # 如果是积极情感词poscount += 1   # 积极得分+1for w in seg_sent[s:i]:poscount = match(w, poscount)s = i + 1  # 记录情感词的位置变化elif word in negdict:  # 如果是消极情感词negcount += 1 # 消极得分+1for w in seg_sent[s:i]:negcount = match(w, negcount)s = i + 1 # 记录情感词位子变化# 如果是感叹号,表示已经到本句句尾elif word == "!".encode('utf8').decode("utf-8") or word == "!".encode('utf8').decode('utf-8'):for w2 in seg_sent[::-1]:  # 倒序扫描感叹号前的情感词,发现后权值+2,然后退出循环if w2 in posdict:poscount += 2breakelif w2 in negdict:negcount += 2breaki += 1# print("poscount,negcount", poscount, negcount)single_review_senti_score.append(transform_to_positive_num(poscount, negcount))   # 对得分做最后处理pos_result, neg_result = 0, 0   # 分别记录积极情感总得分和消极情感总得分for res1, res2 in single_review_senti_score:  # 每个分句循环累加pos_result += res1neg_result += res2print(pos_result, neg_result)result = pos_result - neg_result   # 该条文章情感的最终得分result = round(result, 1)return result"""
# 测试
weibo_sent = "这手机的画面挺好,操作也比较流畅。不过拍照真的太烂了!系统也不好。"
score = single_review_sentiment_score(weibo_sent)
print score
"""# 分析test_data.txt 中的所有文章,返回一个列表,列表中元素为(分值,文章)元组
def run_score():fp_test = open('D:/untitled/To_be_processed/chinese_weibo.txt', 'r')   # 待处理数据contents = []for content in fp_test.readlines():content = content.strip()content = content.encode('utf8').decode("utf8")contents.append(content)fp_test.close()results = []for content in contents:score = single_review_sentiment_score(content)  # 对每条文章调用函数求得打分results.append((score, content))   # 形成(分数,文章)元组return results# 将(分值,句子)元组按行写入结果文件test_result.txt中
def write_results(results):fp_result = open('test_result.txt', 'a')for result in results:fp_result.write(str(result[0]))fp_result.write(' ')fp_result.write(result[1])fp_result.write('\n')fp_result.close()#求取测试文件中的正负极性的文章比,正负极性分值的平均值比,正负分数分别的方差
def handel_result(results):# 正极性文章数量,负极性文章数量,中性文章数量,正负极性比值pos_number, neg_number, mid_number, number_ratio = 0, 0, 0, 0# 正极性平均得分,负极性平均得分, 比值pos_mean, neg_mean, mean_ratio = 0, 0, 0# 正极性得分方差,负极性得分方差pos_variance, neg_variance, var_ratio = 0, 0, 0pos_list, neg_list, middle_list, total_list = [], [], [], []for result in results:total_list.append(result[0])if result[0] > 0:pos_list.append(result[0])   # 正极性分值列表elif result[0] < 0:neg_list.append(result[0])   # 负极性分值列表else:middle_list.append(result[0])#################################各种极性文章数量统计pos_number = len(pos_list)neg_number = len(neg_list)mid_number = len(middle_list)total_number = pos_number + neg_number + mid_numbernumber_ratio = pos_number / neg_numberpos_number_ratio = round(float(pos_number)/float(total_number), 2)neg_number_ratio = round(float(neg_number)/float(total_number), 2)mid_number_ratio = round(float(mid_number)/float(total_number), 2)text_pos_number = "积极文章条数为 " + str(pos_number) + " 条,占全部文章比例的 %" + str(pos_number_ratio*100)text_neg_number = "消极文章条数为 " + str(neg_number) + " 条,占全部文章比例的 %" + str(neg_number_ratio*100)text_mid_number = "中性情感文章条数为 " + str(mid_number) + " 条,占全部文章比例的 %" + str(mid_number_ratio*100)##################################正负极性平均得分统计pos_array = np.array(pos_list)neg_array = np.array(neg_list)    # 使用numpy导入,便于计算total_array = np.array(total_list)pos_mean = pos_array.mean()neg_mean = neg_array.mean()total_mean = total_array.mean()   # 求单个列表的平均值mean_ratio = pos_mean / neg_meanif pos_mean <= 6:                 # 赋予不同的情感等级text_pos_mean = emotion_level4else:text_pos_mean = emotion_level5if neg_mean >= -6:text_neg_mean = emotion_level2else:text_neg_mean = emotion_level1if total_mean <= 6 and total_mean >= -6:text_total_mean = emotion_level3elif total_mean > 6:text_total_mean = emotion_level4else:text_total_mean = emotion_level2##################################正负进行方差计算pos_variance = pos_array.var(axis=0)neg_variance = neg_array.var(axis=0)total_variance = total_array.var(axis=0)# var_ratio = pos_variance / neg_varianceprint("pos_variance:", pos_variance, "neg_variance:", neg_variance, "var_ration:", var_ratio)if total_variance > 10:            # 赋予不同的情感波动级别text_total_var = emotion_level7else:text_total_var = emotion_level6################################构成字典返回result_dict = {}result_dict['pos_number'] = pos_number   # 正向文章数result_dict['neg_number'] = neg_number   # 负向文章数result_dict['mid_number'] = mid_number   # 中性文章数result_dict['number_ratio'] = round(number_ratio, 1)  # 正负文章数之比,保留一位小数四舍五入result_dict['pos_mean'] = round(pos_mean, 1)  # 积极情感平均分result_dict['neg_mean'] = round(neg_mean, 1)  # 消极情感平均分result_dict['total_mean'] = round(total_mean, 1) # 总的情感平均得分result_dict['mean_ratio'] = abs(round(mean_ratio, 1))  # 积极情感平均分/消极情感平均分result_dict['pos_variance'] = round(pos_variance, 1)  # 积极得分方差result_dict['neg_variance'] = round(neg_variance, 1)  # 消极得分方差result_dict['total_variance'] = round(total_variance, 1) # 总的情感得分方差result_dict['var_ratio'] = round(var_ratio, 1)  # 积极得分方差/消极得分方差result_dict['text_pos_number'] = text_pos_number   # 各种情感评价result_dict['text_neg_number'] = text_neg_numberresult_dict['text_mid_number'] = text_mid_numberresult_dict['text_pos_mean'] = text_pos_meanresult_dict['text_neg_mean'] = text_neg_meanresult_dict['text_total_mean'] = text_total_meanresult_dict['text_total_var'] = text_total_var"""for key in result_dict.keys():print 'key = %s , value = %s ' % (key, result_dict[key])"""return result_dictif __name__ == '__main__':results = run_score()     # 计算每句话的极性得分,返回list,元素是(得分,文章)write_results(results)    # 将每条文章的极性得分都写入文件result_dict = handel_result(results)   # 计算结果的各种参数,返回字典print(result_dict)

情感分析(判断文章正负向)相关推荐

  1. [Python人工智能] 二十二.基于大连理工情感词典的情感分析和情绪计算

    从本专栏开始,作者正式研究Python深度学习.神经网络及人工智能相关知识.前一篇文章分享了CNN实现中文文本分类的过程,并与贝叶斯.决策树.逻辑回归.随机森林.KNN.SVM等分类算法进行对比.这篇 ...

  2. 深度学习笔记——情感分析

    很早之前就想写一篇关于用深度学习做情感分析的文章,一直拖到现在,拖延症啊.... 什么是情感分析? 情感分析(Sentiment analysis)是自然语言处理(NLP)领域的一个任务,又称倾向性分 ...

  3. NLP在情感分析中的应用(一)

    一.情感分析的介绍 什么是情感分析,简单理解就是你对于某件物体或事物的倾向,喜欢或不喜欢,想要还是不想要其他,就是对于这件事物本身的一种看法 eg:判断一句点评,是好评还是差评 应用场景有: 1.电子 ...

  4. 情感分析项目基础知识总结二

    文章目录 1.情感分析基础: 1.1 什么是情感分析: 1.2 什么是观点: 直接性与比较性的观点: 明确的和含蓄的观点: 1.3 情感分析的范围: 1.4 情感分析的类型: 细粒度情感分析: 情绪检 ...

  5. 自然语言处理前沿研究之细粒度情感分析

    自然语言处理前沿研究之细粒度情感分析 情感分析综述   文本情感分析:又称意见挖掘.倾向性分析等.简单而言,是对带有情感色彩的主观性文本进行分析.处理.归纳和推理的过程.对于意见.情感或观点,我们进行 ...

  6. 情感分析:几乎包括你需要知道的所有(二)

    文章目录 1.情感分析基础: 1.1 什么是情感分析: 1.2 什么是观点: 直接性与比较性的观点: 明确的和含蓄的观点: 1.3 情感分析的范围: 1.4 情感分析的类型: 细粒度情感分析: 情绪检 ...

  7. 情感分析:几乎包括你需要知道的所有(一)

    1.情感分析教程: 有一份几乎为所有人准备的情感分析教程,包括程序员,非程序员,营销人员,数据分析师,代理人,销售人员等等. 在本节中,我们将分享各种各样的教程,以便您可以找到适合自己的情绪分析. 1 ...

  8. kaggle竞赛 | Quora Insincere Question | 文本情感分析

    目录 赛题背景 赛题评价指标 数据集分析 pytorch建模 之前发布了一遍实战类的情感分析的文章,包括微博爬虫,数据分析,相关模型. 可以参考: https://blog.csdn.net/liji ...

  9. 词向量与词向量拼接_中文字词向量和方面词向量联合嵌入情感分析方法与流程...

    本发明涉及一种中文字词向量和方面词向量联合嵌入CNN-LSTM情感分析方法. 背景技术: 近年来,越来越多的用户习惯在网络上发自己对某一事物的看法与评论.如何快速,准确地从互联网海量评论信息中分析所包 ...

最新文章

  1. 2021年大数据Spark(二):四大特点
  2. 分享几个 Pyecharts 技巧,助你画出更直观/炫酷的图表
  3. Activiti 6.x【11】IntermediateEvent
  4. a = 3 中3在栈还是堆_56.堆、栈、方法区(3.0)
  5. SQL优化—— 优化order by语句 || Filesort 的优化
  6. 打开适配器并捕获数据包
  7. 动态语言与静态语言的区别
  8. vi插入模式下的backspace键和方向键“不正常”使用解决方法
  9. 根据twitter的snowflake算法生成唯一ID
  10. mysql mysqld.sock_MySQL笔记-最简单的方法来解决找不到mysqld.sock文件的问题
  11. oracle 表关联索引优化,Oracle执行计划调优-超级大表关联超级小表的性能调优
  12. Oracle GoldenGate 12c中的协同交付(Coordinated Delivery)
  13. ssh连接aix问题与解决
  14. 腾讯回应封杀质疑;王思聪评社交软件;董明珠连任格力董事长;| 极客头条...
  15. 禁用微信浏览器的下拉_解决微信浏览器禁止下拉查看真实域名网址的问题
  16. php图片大马加后门,一次对php大马的后门的简单分析
  17. python 数据shape的理解
  18. Python3 插入排序
  19. 比SQL还好用,又一门国产数据库语言诞生了
  20. 前往华虹下载POS机应用,回来又上传安装卡应用

热门文章

  1. 剑指offer刷题(2)--面向华为
  2. NVDIMM介绍与应用
  3. Scala学习视频心得(一)语言特点、伴生对象
  4. npm i 下载依赖一直报错:git dep preparation failed等
  5. Unity向量投影使用
  6. 服务器停了3个月网站还能恢复吗,网站被降权怎么恢复正常(网站不更新会被降权)...
  7. pycharm中配置华为云服务器
  8. Oracle 查询的十个小技巧
  9. Multi-Task Video Captioning with Video and Entailment Generation阅读笔记
  10. 电子元器件企业面临缺货涨价,SRM协同系统助力企业采购数字化智慧升级