【python自然语言处理】《致我们单纯的小美好》豆瓣短评的情感分析
这个剧的演员大多为目前不太知名的演员,所以有人跟我说她在看的时候,我的第一反应是把书看了吧,后来某一天,一不小心点开第一集,然后没有停下来,男女主也越看越好看了!
刚好前一阵看了一个《猎场》的情感分析,就模仿着写一下,目前还存在不少问题,所以看个热闹就好啦~
进入正题,利用python的snownlp对豆瓣上的部分短评(之所以是部分,是因为数据并没有成功爬取完,目前大概20+页,481条短评)进行情感分析。
放代码:
1. 豆瓣短评获取
import sys
import re
import requests
import codecs
import time
import random
from bs4 import BeautifulSoup
absolute = 'https://movie.douban.com/subject/27008416/comments'
#这里初始化next_page为第一页的链接后半部分,之后的next_page在网页中获得
#start%20+1就是页数,start=0就是第1页,start=20就是第2页,next_page也可以直接计算得出)
next_page = '?start=0&limit=20&sort=new_score&status=P&percent_type='
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36','Connection':'keep-alive'}
def get_data(html):
soup=BeautifulSoup(html,'lxml')
comment_list = soup.select('.comment > p')
next_page= soup.find('a',text='后页 >')['href']
date_nodes = soup.select('..comment-time')
return comment_list,next_page,date_nodes
if __name__ == '__main__':
f_cookies = open('cookie.txt', 'r')
cookies = {}
for line in f_cookies.read().split(';'):
name, value = line.strip().split('=', 1)
cookies[name] = value
#html = requests.get(absolute + next_page, cookies=cookies, headers=header).content
comment_list = []
while (next_page != []):
#print(absolute + next_page)
html = requests.get(absolute + next_page, cookies=cookies, headers=header).content
#下面两句为解决USC-2编码问题
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
html=html.decode().translate(non_bmp_map)
soup = BeautifulSoup(html, 'lxml')
comment_list, next_page,date_nodes = get_data(html)
with open("beautiful_comments.xls", 'a', encoding='utf-8') as f:
for i in range(0,len(comment_list)):
print(comment_list[i])
comment = comment_list[i].get_text().strip().replace("\n", "")
f.writelines((comment,'\n')) #只进行情感分析时,保留每条评论即可
#date= date_nodes[i].get_text().strip()
#f.writelines((comment,',',date,'\n')) 如果想要按照日期进行数据清洗,需要保存到.csv文件下进行
time.sleep(1 + float(random.randint(1, 100)) / 20)
#没有登录的情况下只能看10页,登录之后获得23页,之后无法获得(目前尚未解决)
获得到的数据:
2. 情感分析
from snownlp import SnowNLP
import pandas as pd
import pylab as pl
import numpy as np
txt = open('beautiful_comments.txt','r',encoding='utf-8')
text = txt.readlines()
txt.close()
print('读入成功')
sentences = []
senti_score = []
counts=0
for i in text:
a1 = SnowNLP(i)
a2 = a1.sentiments
sentences.append(i)
senti_score.append(a2)
print(a2)
counts+=1
table = pd.DataFrame(sentences, senti_score)
print(counts)
x = np.arange(1,counts+1,1)
pl.mpl.rcParams['font.sans-serif'] = ['SimHei']
pl.plot(x, senti_score,'or')
x1 = np.arange(1,counts+1,0.001)
pl.hlines(0.5, 0, counts+1, colors = "c", linestyles = "dashed")
pl.title(u'《致我们单纯的小美好》豆瓣短评情感分析')
pl.xlabel(u'短 评 内 容')
pl.ylabel(u'情 感 程 度')
pl.show()
以0.5为界,大于0.5是积极情绪,小于0.5是消极情绪,越远离0.5,情绪程度越明显,从下图中很明显可以看出积极情绪更多,也就是好评更多。
从豆瓣目前的评分还有目前所得的情感分析,这部剧值得安利一波,哈哈,适合小清新
(不过snownlp的准确率、精度并不能算非常高,大家开心就好啦~~~)
3. 词云
import pickle
from os import path
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
def make_worldcloud(file_path):
text_from_file_with_apath = open(file_path,'r',encoding='UTF-8').read()
wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all=False)
wl_space_split = " ".join(wordlist_after_jieba)
print(wl_space_split)
backgroud_Image = plt.imread('huyitian7.jpg')
print('加载图片成功!')
'''设置词云样式'''
stopwords = STOPWORDS.copy()
stopwords.add("哈哈")
stopwords.add("还是")#可以加多个屏蔽词
wc = WordCloud(
width=1024,
height=768,
background_color='white',# 设置背景颜色
mask=backgroud_Image,# 设置背景图片
font_path='font/simsun.ttc', # 设置中文字体,若是有中文的话,这句代码必须添加,不然会出现方框,不出现汉字
max_words=300, # 设置最大现实的字数
stopwords=stopwords,# 设置停用词
max_font_size=400,# 设置字体最大值
random_state=50,# 设置有多少种随机生成状态,即有多少种配色方案
)
wc.generate_from_text(wl_space_split)#开始加载文本
img_colors = ImageColorGenerator(backgroud_Image)
wc.recolor(color_func=img_colors)#字体颜色为背景图片的颜色
plt.imshow(wc)# 显示词云图
plt.axis('off')# 是否显示x轴、y轴下标
plt.show()#显示
# 获得模块所在的路径的
d = path.dirname(__file__)
# os.path.join(): 将多个路径组合后返回
wc.to_file(path.join(d, "hyt.jpg"))
print('生成词云成功!')
make_worldcloud('beautiful_comments.txt')
啦啦啦,用的是胡一天的照片,电脑自带画图裁剪的,比较粗糙……不过看起来还是有点帅的哈哈
学习中,请多多指教。万一,万一啊,要是有什么侵权的,麻烦大佬赶紧告诉我,谢谢~
参考资料:
http://blog.youkuaiyun.com/csdnnews/article/details/78591437#reply
http://www.aspku.com/tech/jiaoben/python/266932.html