词云 Python 中的 generate_from_frequencies

12
我正在尝试从CSV文件创建一个词云。作为示例,CSV文件的结构如下:
a,1
b,2
c,4
j,20

它有更多的行,大约1800行左右。第一列是字符串值(名称),第二列是它们对应的频率(整数)。然后,文件被读取,并且键值对行被存储在一个字典(d)中,因为我们稍后将使用它来绘制词云图。
reader = csv.reader(open('namesDFtoCSV', 'r',newline='\n'))
d = {}
for k,v in reader:
    d[k] = v

一旦我们有了充满值的字典,我尝试绘制词云图:
#Generating wordcloud. Relative scaling value is to adjust the importance of a frequency word.
#See documentation: https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py
    wordcloud = WordCloud(width=900,height=500, max_words=1628,relative_scaling=1,normalize_plurals=False).generate_from_frequencies(d)
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    plt.show()
But an error is thrown:

    Traceback (most recent call last):
    File ".........../script.py", line 19, in <module>
    wordcloud = WordCloud(width=900,height=500, max_words=1628,relative_scaling=1,normalize_plurals=False).generate_from_frequencies(d)
    File "/usr/local/lib/python3.5/dist-packages/wordcloud/wordcloud.py", line  360, in generate_from_frequencies
    for word, freq in frequencies]
    File "/usr/local/lib/python3.5/dist-packages/wordcloud/wordcloud.py", line 360, in <listcomp>
    for word, freq in frequencies]
    TypeError: unsupported operand type(s) for /: 'str' and 'float

最后,文档中写道:
def generate_from_frequencies(self, frequencies, max_font_size=None):
    """Create a word_cloud from words and frequencies.
    Parameters
    ----------
    frequencies : dict from string to float
        A contains words and associated frequency.
    max_font_size : int
        Use this font-size instead of self.max_font_size
    Returns
    -------
    self

所以,我不明白为什么在满足函数要求的情况下会出现这个错误。希望有人能帮助我,谢谢。
注意:
我使用的是worldcloud 1.3.1版本。
2个回答

9
这是因为您的字典中的值是字符串,但是wordcloud需要整数或浮点数。运行您的代码后,检查您的字典d,我得到以下结果。
In [12]: d

Out[12]: {'a': '1', 'b': '2', 'c': '4', 'j': '20'}

注意,数字周围的 ' ' 意味着它们实际上是字符串。
解决这个问题的一种不太正规的方法是在你的 FOR 循环中将 v 强制转换为整数,就像这样:
d[k] = int(v)

我认为这种方法有些投机取巧,因为它可以处理整数,但是如果输入中有浮点数,则可能会出现问题。
此外,Python错误信息往往难以阅读。上面的错误信息可以理解为:
script.py", line 19

TypeError: unsupported operand type(s) for /: 'str' and 'float

我的文件第19行或之前出现了类型错误。让我查看一下数据类型,看看字符串和浮点数之间是否有不匹配的地方...

以下代码对我有效:

import csv
from wordcloud import WordCloud
import matplotlib.pyplot as plt

reader = csv.reader(open('namesDFtoCSV', 'r',newline='\n'))
d = {}
for k,v in reader:
    d[k] = int(v)

#Generating wordcloud. Relative scaling value is to adjust the importance of a frequency word.
#See documentation: https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py
wordcloud = WordCloud(width=900,height=500, max_words=1628,relative_scaling=1,normalize_plurals=False).generate_from_frequencies(d)

plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

这对我有用,谢谢,我一直在打转。 - Magnetar

1
# LEARNER CODE START HERE
file_c=""
for index, char in enumerate(file_contents):
    if(char.isalpha()==True or char.isspace()):
        file_c+=char
file_c=file_c.split()
file_w=[]
for word in file_c:
    if word.lower() not in uninteresting_words and word.isalpha()==True:
    file_w.append(word)
frequency={}
for word in file_w:
    if word.lower() not in frequency:
        frequency[word.lower()]=1
    else:
        frequency[word.lower()]+=1
#wordcloud
cloud = wordcloud.WordCloud()
cloud.generate_from_frequencies(frequency)
return cloud.to_array()

最好简要解释一下代码的工作原理。 - Agile_Eagle
请解释为什么这是一个解决方案。你的解决方案做了什么,它如何解决问题。(它还应该对那些因为遇到类似问题而查找此问题的人有教育作用。) - user1986815

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接