Python爬取《你好李焕英》豆瓣短评并基于SnowNLP做情感分析

您所在的位置:网站首页 python爬取豆瓣小说 Python爬取《你好李焕英》豆瓣短评并基于SnowNLP做情感分析

Python爬取《你好李焕英》豆瓣短评并基于SnowNLP做情感分析

2024-04-11 02:55| 来源: 网络整理| 查看: 265

爬取过程在这里:

Python爬取你好李焕英豆瓣短评并利用stylecloud制作更酷炫的词云图

本文基于前文爬取生成的douban.txt,基于SnowNLP做情感分析。

依赖库:

豆瓣镜像比较快:

pip install snownlp -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple

在这里插入图片描述

初识SnowNLP:

SnowNLP是一个常用的Python文本分析库,是受到TextBlob启发而发明的。由于当前自然语言处理库基本都是针对英文的,而中文没有空格分割特征词,Python做中文文本挖掘较难,后续开发了一些针对中文处理的库,例如SnowNLP、Jieba、BosonNLP等。

Snownlp主要功能包括:

中文分词(算法是Character-Based Generative Model)词性标注(原理是TnT、3-gram 隐马)情感分析文本分类(原理是朴素贝叶斯)转换拼音、繁体转简体提取文本关键词(原理是TextRank)提取摘要(原理是TextRank)、分割句子文本相似(原理是BM25) 情感分析实战:

SnowNLP情感分析是基于情感词典实现的,其简单的将文本分为两类,积极和消极,返回值为情绪的概率,也就是情感评分在[0,1]之间,越接近1,情感表现越积极,越接近0,情感表现越消极。

下面对爬取的豆瓣电影《你好李焕英》评论进行情感分析。

情感各分数段出现频率

首先统计各情感分数段出现的评率并绘制对应的柱状图。

对douban.txt文件逐行进行情感倾向值计算,代码如下:

# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- from snownlp import SnowNLP import matplotlib.pyplot as plt import numpy as np source = open("douban.txt","r", encoding='utf8') line = source.readlines() sentimentslist = [] for i in line: s = SnowNLP(i) print(s.sentiments) sentimentslist.append(s.sentiments) plt.hist(sentimentslist, bins = np.arange(0, 1, 0.01), facecolor = 'g') plt.xlabel('Sentiments Probability') plt.ylabel('Quantity') plt.title('Analysis of Sentiments') plt.show()

输出结果如下图所示: 在这里插入图片描述

对应的情感倾向值如下(部分): 在这里插入图片描述

情感波动分析

接下来分析评论,每条评论的波动情况,代码如下所示:

# -*- coding: utf-8 -*- # 区间[0,1] from snownlp import SnowNLP import matplotlib.pyplot as plt import numpy as np source = open("douban.txt","r", encoding='utf8') line = source.readlines() sentimentslist = [] for i in line: s = SnowNLP(i) print(s.sentiments) sentimentslist.append(s.sentiments) plt.plot(np.arange(0, 166, 1), sentimentslist, 'b-') plt.xlabel('Number') plt.ylabel('Sentiment') plt.title('Analysis of Sentiments') plt.show()

输出结果如下所示,接近1.0代表好评,可以看出好评率很高。 在这里插入图片描述

改进

将情感区间从[0, 1.0]转换为[-0.5, 0.5],这样的曲线更加直观,位于0以上的是积极评论,反之消极评论。 修改代码如下:

# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from snownlp import SnowNLP #获取情感分数 source = open("douban.txt","r", encoding='utf8') line = source.readlines() sentimentslist = [] for i in line: s = SnowNLP(i) print(s.sentiments) sentimentslist.append(s.sentiments) #区间转换为[-0.5, 0.5] result = [] i = 0 while i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3