使用Python生成仅含字母的词云时报AttributeError错误如何解决
问题原因
你的代码存在4个可直接导致运行报错的问题:
- 未提前导入
wordcloud库提供的WordCloud类,WordCloud不是Python内置功能,也不是字典的内置方法 - 错误地从词频统计字典
count调用WordCloud()方法,触发AttributeError报错 - 调用
generate_from_frequencies时传入了未初始化完成的cloud对象,实际需要传入你统计好的词频字典count - 原代码中
with open块下方的代码没有正确缩进,会直接触发Python缩进语法错误
修复步骤
- 先安装依赖库:
pip install wordcloud
- 使用修正后的代码:
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
相关产品推荐
相关产品推荐

