我正在尝试使用:https ://github.com/amueller/word_cloud生成带有掩码的词云,但我在初始设置时遇到了一些问题。作者说,如果您不在 Ubuntu 中,则必须将 FONT_PATH 设置为字体的路径。我正在运行 Ubuntu,但我遇到了这个错误:
错误:
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
所以我决定导出字体路径:
~/wordcloud$ echo $FONT_PATH
/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
但我仍然遇到同样的错误。决定了,好吧,如果我把它添加到脚本中呢:
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)
但是还是不行。