6.6 绘制词云图
“词云”就是通过形成“关键词云层”或“关键词渲染”,对网络文本中出现频率较高的“关键词”的视觉上的突出。在本节的内容中,将通过两个实例讲解使用Python语言创建词云图的方法。
6.6.1 绘制B站词云图
编写实例文件BiliBili.py,功能抓取B站排行榜的信息,然后提取排行榜前50名视频的所有标签信息,最后将提取的标签文本添加到词云图中。文件BiliBili.py的具体实现代码如下所示。
sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding='gb18030')#编码
url='https://www.bilibili.com/ranking'#B站排行榜链接
response=requests.get(url)
html=response.text
video_list=re.findall(r'<a href="(.*?)" target="_blank">', html)#B站排行榜链接列表
label_list=[]
video_name=re.findall(r'target="_blank" class="title">(.*?)</a><!----><div class="detail"><span class="data-box">',html)#B站排行榜视频名
video_play=re.findall(r'<i class="b-icon play"></i>(.*?)</span>', html)#播放数
video_view=re.findall(r'<i class="b-icon view"></i>(.*?)</span><a target="_blank"',html)#评论数
video_up=re.findall(r'<i class="b-icon author"></i>(.*?)</span></a>', html)#UP主
for i in range (0, 100):
print('%d.'%(i+1), end='')
print('%-65s'%video_name[i],end='')
print('up主: %-15s'%video_up[i], end='')
print('播放数: %-8s'%video_play[i], end='')
print('评论数: %s'%video_view[i])#循环输出视频名、 UP主、 播放数、 评论数
for video in video_list:
video_response=requests.get(video)
video_html=video_response.text
video_label=re.findall(r'target="_blank">(.*?)</a>', video_html)
for label in video_label:
label_list.append(label)#把排行榜视频的所有标签添加进label_list
label_string=" ".join(label_list)#把label_list转string型
w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',
font_path='msyh.ttc')
w.generate(label_string)
w.to_file('BiliBili.png')
执行后会创建一幅名为“BiliBili.png”的词云图,效果如图6-15所示。
图6-15 词云图效果
6.6.2 绘制知乎词云图
编写实例文件zhihu.py,功能抓取知乎热榜的信息,然后提取排行榜前50名信息的所有标签信息,最后将提取的标签文本添加到词云图中。文件zhihu.py的具体实现代码如下所示。
import matplotlib.pyplot as plt
sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding='gb18030')#编码
headers={
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
'Referer':'https://www.zhihu.com/',
'Cookie':'_zap=d39ea996-dcf8-444d-bbb0-2cda0cafc120;
response=requests.get("https://www.zhihu.com/hot",headers=headers)#知乎热榜链接
html=response.text
html_list=re.findall(r'</div></div><div class="HotItem-content"><a href="(.*?)" title="', html)#抓取所有热榜话题链接
print(html_list)
print(len(html_list))
label_list=[]
for i in range(0, 50):
hot_response=requests.get(html_list[i], headers=headers)#必须要有headers,要不然无法访问
hot_html=hot_response.text
hot_label=re.findall(r'keywords" content="(.*?)"/><meta itemProp="answerCount"', hot_html)#抓取所有热词
hot_name=re.findall(r'><title data-react-helmet="true">(.*?)? - 知乎</title><meta name="viewport"', hot_html)#抓取标题
print('%d.'%(i+1), end='')
for i in range(len(hot_label)):
label_list.append(hot_label[i])
print(label_list)
label_string=" ".join(label_list)#转换为string型
print(label_string)
w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',
font_path='msyh.ttc')
w.generate(label_string)
w.to_file('zhihu.png')#生成词云图片
执行后会创建一幅名为“zhihu.png”的词云图,效果如图6-16所示。
图6-16 词云图效果