WordCloud词云实现电视剧评论可视化

以腾讯视频平台上电视剧《琅琊榜》为例,爬取评论进行可视化汇总

1、首先浏览器打开腾讯视频网站播放《琅琊榜》,按F12进入开发者工具调试,点击网页上“查看更多评论”然后查看网络日志,可以看到右侧请求的记录

在浏览器打开查看,url为https://video.coral.qq.com/varticle/1210555765/comment/v2?callback=_varticle1210555765commentv2&orinum=10&oriorder=o&pageflag=1&cursor=6681749993978056282&scorecursor=0&orirepnum=2&reporder=o&reppageflag=1&source=132&_=1593935252679,可以看到这个文件就是评论需要加载的数据,content参数对应的就是评论。

继续“查看更多评论”,可以发现这些数据文件的url变化只有cursor参数和最后一个_参数,而文件中last对应的值就是下一页url中的cursor参数,_参数是页数(递增就行),根据这个思路可以写出python脚本爬取评论。

2、使用wordcloud模块对评论进行可视化汇总

python3代码如下:

# -*- codeing = utf-8 -*-
# @Time : 2020/7/5 9:50
# @Author : loadding...
# @File : test_comment.py
# @Software : PyCharm

import urllib.request, urllib.error
import re
import jieba  # 中文分词模块,pip install jieba安装
from matplotlib import pyplot as plt  # 绘图,数据可视化
from wordcloud import WordCloud  # 词云,根据文本中的词频,对内容进行可视化的汇总
from PIL import Image
import numpy as np

# 腾讯视频《琅琊榜》短评可视化汇总

# 模拟浏览器头部信息,腾讯服务器发送请求
head = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36M'
}
# 评论词库
comment = ''
lastid = "0"
for i in range(1, 100):  # 页数,1页10条评论,统计100页共1000条评论
    pagenum = 1593926451652 + i
    url = 'https://video.coral.qq.com/varticle/1210555765/comment/v2?callback=_varticle1210555765commentv2&orinum=10&oriorder=o&pageflag=1&cursor=0&scorecursor=' + lastid + '&orirepnum=2&reporder=o&reppageflag=1&source=132&_=' + str(
        pagenum)
    request = urllib.request.Request(url, headers=head)
    response = urllib.request.urlopen(request)
    data = response.read().decode('utf-8')
    lastid = re.compile('"last":"(.*?)"').findall(data)[0]  # 下一页url中的id
    content = re.compile('"content":"(.*?)"').findall(data)  # 评论内容(列表)

    for j in content:
        comment = comment + j

# 对评论进行分词
cut = jieba.cut(comment)
string = ' '.join(cut)

# 加载背景图
img = Image.open('tree.jpg')
img_array = np.array(img)  # 将图片转换为数组(三维)
# print(img_array.shape)#(709, 1000, 3)(高,宽,位数)
wc = WordCloud(
    background_color='white',
    mask=img_array,
    font_path='msyh.ttc',  # 微软雅黑,字体所在位置:C:\Windows\Fonts
    collocations=False  # 不统计搭配词
)
wc.generate_from_text(string)

# 绘制图片
fig = plt.figure(1)
plt.imshow(wc)  # imshow()函数负责对图像进行处理,并显示其格式,而plt.show()则是将plt.imshow()处理后的函数显示出来
plt.axis('off')  # 是否显示坐标轴

# 保存图片
plt.savefig('comment_tree.jpg', dpi=500)
plt.show()  # 显示生成的词云图片,注意保存与显示的顺序

3、结果

词云背景图片tree.jpg如下:

评论可视化结果为:

猜你喜欢

转载自blog.csdn.net/qq_41137110/article/details/107139774