I am trying to generate a word cloud using the WordCloud module in Python, however I see the following error whenever I call .generate
Traceback (most recent call last):
File "/mnt/6db3226b-5f96-4257-980d-bb8ec1dad8e7/test.py", line 4, in <module>
wc.generate("foo bar foo bar hello world")
File "/home/mjc/.local/lib/python3.10/site-packages/wordcloud/wordcloud.py", line 639, in generate
return self.generate_from_text(text)
File "/home/mjc/.local/lib/python3.10/site-packages/wordcloud/wordcloud.py", line 621, in generate_from_text
self.generate_from_frequencies(words)
File "/home/mjc/.local/lib/python3.10/site-packages/wordcloud/wordcloud.py", line 453, in generate_from_frequencies
self.generate_from_frequencies(dict(frequencies[:2]),
File "/home/mjc/.local/lib/python3.10/site-packages/wordcloud/wordcloud.py", line 508, in generate_from_frequencies
box_size = draw.textbbox((0, 0), word, font=transposed_font, anchor="lt")
File "/usr/lib/python3/dist-packages/PIL/ImageDraw.py", line 671, in textbbox
raise ValueError("Only supported for TrueType fonts")
ValueError: Only supported for TrueType fonts
As it stands, I am trying to create a very simple example WordCloud
import matplotlib.pyplot as plt
from wordcloud import WordCloud
wc = WordCloud(background_color="white", font_path="./arial.ttf", width=800, height=400)
wc.generate("foo bar foo bar hello world")
plt.axis("off")
plt.imshow(wc)
plt.savefig("test.png")
plt.show()
Where arial.ttf
is downloaded from https://www.freefontspro.com/14454/arial.ttf and placed in the same directory as test.py
. I am using Ubuntu 22.04 and Python 3.10.6.
I was expecting to generate a word cloud from the input "foo bar foo bar hello world", however see the error ValueError: Only supported for TrueType fonts
despite passing a ttf to the font_path
argument.
Any help on resolving this is appreciated!
2
Answers
I could not reproduce your error with Python 3.10 even after downloading the same font – though I am on macOS.
The only thing I can imagine is that your PIL doesn’t support TrueType fonts, so you can check with:
Sample Output
Or, more speedily – since we are only interested in "freetype" lines:
Then you may need to install
freetype
with a command something like – not too sure of the exact package name:These work for me:
pip install –upgrade pip
pip install –upgrade Pillow
Tell me if it doesn’t work