【问题标题】:How to generate word cloud from CSV file with word frequencies如何从具有词频的 CSV 文件生成词云
【发布时间】:2017-04-06 02:51:51
【问题描述】:

我有一个包含以下格式数据的 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'

【问题讨论】:

  • 当你从csv读取数字时,它作为字符串加载,所以你需要将它转换为int

标签: python csv word-cloud


【解决方案1】:

将值转换为浮点数。

d[k] = float(v)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多