我正在尝试显示词云图像,但出现值错误:我们至少需要 1 个单词来绘制词云,得到 0



def calculate_frequency(file_contents(:#这是一个可以用来处理文本的标点符号和无趣单词列表标点符号=''!((-[]{};:'"\,<>./?@#$%^&*_~''"无趣单词=["the"、"a"、"to"、"if"、"is"、"it"、"of"、"and"、"or"、"an"、"as"、"i"、"me"、"my"\"我们"、"我们的"、"自己的"、"你"、"你的"、"他"、"她"、"他"、"他的"、"她"、"她的"、"它"、"它们"、"他们"\"their"、"what"、"which"、"who"、"which"、"this"、"that"、"am"、"are"、"was"、"were"、"be"、"been"、"being"\"有"、"有","曾"、"做"、"确实"、"但是"、"在"、"由"、"与"、"来自"、"这里"、"何时"、"何处"、"如何"\

frequencies={}
def iterate():
words=file_contents.split()
for word in words:
if word not in uninteresting_words and word not in punctuations:
if word not in frequencies and word in file_contents:
frequencies[word]+=1
else:
frequencies[word]=1   


#wordcloud
cloud = wordcloud.WordCloud()
cloud.generate_from_frequencies(frequencies)
return cloud.to_array()


myimage = calculate_frequencies(file_contents)
plt.imshow(myimage, interpolation = 'nearest')
plt.axis('off')
plt.show()

我从未使用过这个库,所以如果这不起作用,请随时告诉我。

首先,这个if语句似乎被翻转了:

if word not in frequencies and word in file_contents:
frequencies[word]+=1
else:
frequencies[word]=1

切换到

if word in frequencies and word in file_contents:
...

接下来,您永远不会调用iterate函数来填充频率。在调用wordcloud之前执行此操作。

最后,另一个SO的答案放在文本中:

wordcloud.generate_from_frequencies(frequencies=frequencies)

希望在做了这些事情之后,它会起作用。

相关内容

最新更新