Python WordCloud模块报错:仅支持TrueType字体问题咨询
ValueError: Only supported for TrueType fonts when using WordCloud with TTF font
尝试使用Python的WordCloud模块生成词云时,调用
.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使用的示例代码:
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()已将下载的arial.ttf放在脚本同一目录,运行环境为Ubuntu 22.04、Python 3.10.6,传入TTF字体路径仍报错,寻求解决方案。
解决方案
1. 验证字体文件的有效性
下载的arial.ttf可能并非标准TrueType格式,或文件损坏。可以:
- 用系统字体查看器打开该文件,确认能正常显示字体内容;
- 替换为系统自带的可靠TrueType字体,比如Ubuntu下的
/usr/share/fonts/truetype/freefont/FreeSans.ttf,这个是系统预安装的TrueType字体,兼容性有保障。
2. 确保字体路径正确
相对路径可能因运行脚本的工作目录不同而失效,建议使用绝对路径:
import os from wordcloud import WordCloud import matplotlib.pyplot as plt # 获取脚本所在的绝对目录 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接字体文件的绝对路径 font_path = os.path.join(script_dir, "arial.ttf") wc = WordCloud(background_color="white", font_path=font_path, width=800, height=400) wc.generate("foo bar foo bar hello world") plt.axis("off") plt.imshow(wc) plt.savefig("test.png") plt.show()
3. 更新依赖包版本
Pillow(PIL)和WordCloud的版本不兼容可能导致该问题,执行以下命令更新:
pip install --upgrade pillow wordcloud
4. 测试最小化示例
先排除matplotlib的影响,运行最简脚本验证词云生成:
from wordcloud import WordCloud import os script_dir = os.path.dirname(os.path.abspath(__file__)) font_path = os.path.join(script_dir, "arial.ttf") # 或替换为系统字体路径 wc = WordCloud(font_path=font_path) wc.generate("foo bar foo bar hello world") wc.to_file("test.png")
如果该脚本能生成图片,说明问题出在matplotlib的调用环节,再逐步排查。
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

