在 Pycharm 中输入下面代码后,出现报错 ValueError: We need at least 1 word to plot a word cloud, got 0. 的原因是 text 变量中没有任何内容,导致无法生成词云图。

import requests
from bs4 import BeautifulSoup
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 爬取网页内容
url = 'https://www.bilibili.com/video/BV1MN41187U6?p=1&vd_source=9c183665340588179721abd85713714d'
response = requests.get(url)
html = response.text

# 解析网页内容,找到弹幕和评论的标签或类名
soup = BeautifulSoup(html, 'html.parser')
danmu_tags = soup.select('.bui-collapse-wrap .list-item.reply-wrap .text')  # 弹幕标签
comment_tags = soup.select('.comment-list .list-item .text')  # 评论标签

# 获取弹幕和评论的内容
danmus = [danmu.text for danmu in danmu_tags]
comments = [comment.text for comment in comment_tags]

# 将弹幕和评论内容合并
text = ' '.join(danmus + comments)

# 生成弹幕词云图
danmu_wordcloud = WordCloud(font_path='msyh.ttc', background_color='white').generate(text)
plt.figure(figsize=(10, 6))
plt.imshow(danmu_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('弹幕词云图')
plt.show()

# 生成评论词云图
comment_wordcloud = WordCloud(font_path='msyh.ttc', background_color='white').generate(' '.join(comments))
plt.figure(figsize=(10, 6))
plt.imshow(comment_wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('评论词云图')
plt.show()

可能的解决方法是:

  1. 检查网页内容是否正确获取到,可以通过打印 html 变量来查看。
  2. 检查弹幕和评论标签或类名是否正确,可以通过打印 danmu_tagscomment_tags 来查看。
  3. 检查是否存在弹幕和评论内容,可以通过打印 danmuscomments 来查看。

如果确认以上步骤都正确,仍然出现报错,则可能是网页的结构发生了变化,需要根据实际情况修改代码。

Pycharm 报错 ValueError: We need at least 1 word to plot a word cloud, got 0. 解决方法

原文地址: https://www.cveoy.top/t/topic/qzPH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录