从字典中生成wordcloud时遇到问题



我正在做一门学习Python的在线课程,但我被一项作业卡住了。任务是创建一个字典,过滤掉标点符号和常见单词,最终生成单词云。这就是我得到的:

def calculate_frequencies(file_contents):
# Here is a list of punctuations and uninteresting words you can use to process your text
punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", 
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", 
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", 
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", 
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]
boek = {}
for word in file_contents.split():
if word != uninteresting_words and word.isalpha():
if word not in boek:
boek[word] = 0
boek[word] += 1
#wordcloud
cloud = wordcloud.WordCloud()
cloud.generate_from_frequencies(boek.keys)
return cloud.to_array()

这不会返回任何错误。然而,应该生成世界云的细胞确实是:

myimage = calculate_frequencies(file_contents)
plt.imshow(myimage, interpolation = 'nearest')
plt.axis('off')
plt.show()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-62-fd0f708f372c> in <module>
1 # Display your wordcloud image
2 
----> 3 myimage = calculate_frequencies(file_contents)
4 plt.imshow(myimage, interpolation = 'nearest')
5 plt.axis('off')
<ipython-input-61-a23e5e09adaa> in calculate_frequencies(file_contents)
20 
21     #wordcloud
---> 22     cloud = wordcloud.WordCloud()
23     cloud.generate_from_frequencies(boek.keys)
24     return cloud.to_array()
NameError: name 'wordcloud' is not defined

我做错了什么,更重要的是为什么?非常感谢你的帮助!

出现错误的原因是您没有在程序中的任何位置定义"wordcloud"。

在您的错误所指向的行中,您有

cloud = wordcloud.WordCloud()

您尚未定义第一个"wordcloud"(不要与wordcloud((混淆(。这可能意味着您正在尝试使用尚未导入的内容,或者您忘记在程序的早期定义此内容。

最新更新