Python爬取腾讯视频斗罗大陆弹幕并生成词云
使用Python爬取腾讯视频斗罗大陆第一集弹幕并生成词云
本程序使用Python语言,通过爬取腾讯视频斗罗大陆第一集的弹幕数据,并将其保存到Excel表格中,最后使用词云图展示弹幕中的关键词分布。
主要步骤:
-
加载第三方库
import requests from bs4 import BeautifulSoup import openpyxl import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt -
爬取弹幕数据
# 爬取腾讯视频斗罗大陆第一集弹幕 url = 'https://mfm.video.qq.com/danmu?otype=json×tamp=1617304500&target_id=931421933&count=1000' response = requests.get(url) danmus = response.json()['comments'] -
将弹幕信息保存到Excel表格中
# 保存弹幕到Excel表中 wb = openpyxl.Workbook() ws = wb.active ws.title = '弹幕' ws.append(['序号', '弹幕内容', '弹幕时间', '点赞数']) for i, danmu in enumerate(danmus): ws.append([i+1, danmu['content'], danmu['timepoint'], danmu['upcount']]) wb.save('danmu.xlsx') -
统计弹幕中的关键词
# 统计弹幕中的关键词 words = [] for danmu in danmus: words += jieba.lcut(danmu['content']) word_count = {} for word in words: if len(word) < 2: continue if word in word_count: word_count[word] += 1 else: word_count[word] = 1 -
生成词云图
# 生成词云图 wc = WordCloud(background_color='white', font_path='msyh.ttc') wc.generate_from_frequencies(word_count) plt.imshow(wc) plt.axis('off') plt.show()
代码说明:
- 使用
requests库获取网页数据。 - 使用
BeautifulSoup4库解析网页内容。 - 使用
openpyxl库将数据保存到Excel表格中。 - 使用
jieba库进行中文分词。 - 使用
WordCloud库生成词云图。 - 使用
matplotlib.pyplot库显示词云图。
运行结果:
程序运行后,会生成一个名为danmu.xlsx的Excel表格,其中包含爬取的弹幕信息。同时会生成一个词云图,显示弹幕中出现的关键词。
注意:
- 腾讯视频的网站可能会更改,导致程序无法正常运行。
- 程序中使用了
font_path='msyh.ttc'指定了词云图使用的字体,你需要确保你的电脑上安装了该字体。
总结:
本程序演示了如何使用Python爬取腾讯视频弹幕信息,并使用词云图展示弹幕中的关键词分布。你可以根据需要修改代码,爬取其他网站的弹幕数据,并进行其他数据分析。
原文地址: https://www.cveoy.top/t/topic/f1dc 著作权归作者所有。请勿转载和采集!