Jaafa
Jaafa

Reputation: 141

How to generate word cloud from CSV file with word frequencies

I have a CSV file with data in the following format

column1 column2
hello     1
film      9
chicken   20
etc       etc

How can I generate a word cloud using such a file with python? I tried using the wordcloud package by Andreas Mueller but it doesn't accept csv. I also tried using the generate_from_frequencies option as such

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) 

But kept getting an error as below.

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'

Upvotes: 3

Views: 2672

Answers (1)

xrisk
xrisk

Reputation: 3898

Convert the value to an float.

d[k] = float(v)

CSVreader gives you strings, whereas generate_from_frequencies requires a dict from str to float.

Upvotes: 2

Related Questions