You need to enable JavaScript to run this app. 使用Python生成仅含字母的词云时报AttributeError错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Python生成仅含字母的词云时报AttributeError错误如何解决

问题原因

你的代码存在4个可直接导致运行报错的问题:

  • 未提前导入wordcloud库提供的WordCloud类,WordCloud不是Python内置功能,也不是字典的内置方法
  • 错误地从词频统计字典count调用WordCloud()方法,触发AttributeError报错
  • 调用generate_from_frequencies时传入了未初始化完成的cloud对象,实际需要传入你统计好的词频字典count
  • 原代码中with open块下方的代码没有正确缩进,会直接触发Python缩进语法错误

修复步骤

  1. 先安装依赖库:
pip install wordcloud
  1. 使用修正后的代码:
from wordcloud import WordCloud

count = dict()
with open("worldcloud.txt", encoding="utf-8") as f:
    for line in f:
        words = line.split()
        for word in words:
            if word.isalpha():
                count[word] = count.get(word, 0) + 1

cloud = WordCloud()
cloud.generate_from_frequencies(count)
cloud.to_file("myfile.jpg")

内容的提问来源于stack exchange,提问作者Muhammad Idrees Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 00:45:03