python爬取B站某一个视频所有的弹幕并绘制云图
时间: 2025-06-22 13:48:23 浏览: 13
### 使用Python抓取Bilibili视频全部弹幕并制作词云可视化
#### 准备工作
为了实现这一目标,需要安装一些必要的库。可以通过pip来安装这些依赖项:
```bash
pip install requests pandas lxml wordcloud matplotlib jieba
```
#### 获取弹幕数据
通过`requests`库发送HTTP请求至指定的弹幕链接地址,并利用`lxml.etree`解析返回的内容,提取其中所有的弹幕文本。
```python
import requests
from lxml import etree
import pandas as pd
url = 'https://comment.bilibili.com/123072475.xml'
response = requests.get(url)
xml_data = etree.fromstring(response.content)
# 提取出所有弹幕文字信息
danmu_texts = xml_data.xpath("//d/text()")
df_danmu = pd.DataFrame(danmu_texts, columns=["content"])
print(df_danmu.head())
```
#### 数据预处理
对于中文来说,在构建词频统计之前通常还需要分词操作。这里采用结巴(`jieba`)来进行中文分词处理;另外去除停用词也是很重要的一步,可以提高最终生成词云的质量。
```python
import jieba
def preprocess_text(text):
words = jieba.lcut(text.strip()) # 对每条弹幕做分词
clean_words = []
with open('stopwords.txt', mode='r', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
for w in words:
if not any(char.isdigit() or char.isalpha() for char in w): # 去除非汉字字符
continue
elif len(w)>1 and w.lower() not in stopwords: # 过滤掉长度小于等于1以及存在于停止词表中的词语
clean_words.append(w)
return " ".join(clean_words)
cleaned_content = df_danmu['content'].apply(preprocess_text).dropna()
word_series = cleaned_content.str.split(expand=True).stack().value_counts()
print(word_series[:10])
```
#### 构建词云图像
最后借助于`WordCloud`类创建一个自定义样式的词云对象,并调用其方法绘制出图形化表示形式。
```python
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wc = WordCloud(font_path="simhei.ttf", background_color="white").generate_from_frequencies(word_series)
plt.figure(figsize=(10, 6))
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
```
上述过程展示了如何使用Python从网络上获取特定ID下的B站视频弹幕数据[^1],并对收集到的信息进行了简单的清理和转换以便后续分析[^2]。接着运用自然语言处理技术完成对原始语料的有效分割与过滤[^3],从而为下一步形成具有视觉冲击力的文字云奠定了坚实的基础。
阅读全文
相关推荐















