如何从具有字频率的CSV文件生成文字云

时间:2017-04-05 18:48:36

标签: python csv word-cloud

我有一个包含以下格式数据的CSV文件

column1 column2
hello     1
film      9
chicken   20
etc       etc

如何使用python这样的文件生成文字云?我尝试使用Andreas Mueller的wordcloud包,但它不接受csv。我也尝试使用generate_from_frequencies选项

reader = csv.reader(open('wordcount.csv', 'r',newline='\n'))
d = {}

for k,v in reader:
    d[k] = v

 # Generate a word cloud image
 wordcloud = WordCloud().generate_from_frequencies(d) 

但是仍然收到如下错误。

File "wordcloudtest.py", line 22, in <module>
    wordcloud = WordCloud().generate_from_frequencies(d)
  File "C:\Users\Lenovo\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 360, in generate_from_frequenci
    for word, freq in frequencies]
  File "C:\Users\Lenovo\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 360, in <listcomp>
    for word, freq in frequencies]
TypeError: unsupported operand type(s) for /: 'str' and 'float'

1 个答案:

答案 0 :(得分:1)

将值转换为浮点数。

d[k] = float(v)

CSVreader为您提供字符串,而generate_from_frequencies则需要从strfloat的字典。