Python word_cloud not finding font_path after exporting font_path

5.4k views Asked by At

I'm trying to use: https://github.com/amueller/word_cloud to generate a word cloud with a mask, but I'm having some issues with the initial setup. The author says that if you're not in Ubuntu you will have to set FONT_PATH to the path to a font. I'm running Ubuntu but I hit this error:

Error:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    wordcloud = WordCloud().generate(text)
  File "/usr/local/lib/python2.7/dist-packages/wordcloud/wordcloud.py", line 311, in generate
    self.fit_words(self.words_)
  File "/usr/local/lib/python2.7/dist-packages/wordcloud/wordcloud.py", line 179, in fit_words
    font = ImageFont.truetype(self.font_path, font_size)
  File "/usr/lib/python2.7/dist-packages/PIL/ImageFont.py", line 228, in truetype
    return FreeTypeFont(font, size, index, encoding)
  File "/usr/lib/python2.7/dist-packages/PIL/ImageFont.py", line 131, in __init__
    self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource

So I decided to export the font path:

~/wordcloud$ echo $FONT_PATH
/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf

But I'm still hitting the same error. Decided, ok, what if I add this to the script then:

from os import path
from os import environ
import matplotlib.pyplot as plt
from wordcloud import WordCloud

d = path.dirname(__file__)

environ["FONT_PATH"] = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
# Read the whole text.
text = open('constitution.txt').read()
wordcloud = WordCloud().generate(text)

But still no go.

1

There are 1 answers

0
user3580686 On

Use font_path as WordCloud argument.

wordcloud = WordCloud(font_path='/Library/Fonts/Verdana.ttf').generate(text)

It should work.

Best regards robert