Python 词云库 WordCloud 中 'ImageDraw' object has no attribute 'textbbox' 错误的解决方法

在使用 Python 的词云库 WordCloud 生成词云时,你可能会遇到以下错误信息:pythonTraceback (most recent call last): File '...', line ..., in ... wordcloud = WordCloud(...).generate(' '.join(words)) File '...', line ..., in generate return self.generate_from_text(text) File '...', line ..., in generate_from_text self.generate_from_frequencies(words) File '...', line ..., in generate_from_frequencies max_font_size=self.height) File '...', line ..., in generate_from_frequencies box_size = draw.textbbox((0, 0), word, font=transposed_font, anchor='lt')AttributeError: 'ImageDraw' object has no attribute 'textbbox'

错误原因

这个错误通常是由于 Pillow 库版本过低引起的。textbbox 方法是在 Pillow 5.0.0 版本中添加的。如果你的 Pillow 版本低于 5.0.0,就会出现这个错误。

解决方法

要解决这个问题,你需要将 Pillow 库升级到最新版本。你可以使用以下命令升级 Pillow:bashpip install --upgrade Pillow

升级完成后,重新运行你的程序,错误应该就会消失。

代码示例

以下是使用 WordCloud 生成词云的简单示例代码:pythonfrom wordcloud import WordCloudimport matplotlib.pyplot as plt

定义词语列表words = ['Python', 'WordCloud', '词云', '数据可视化', '文本分析']

生成词云wordcloud = WordCloud(width=800, height=600, background_color='white', max_words=50).generate(' '.join(words))

显示词云plt.figure(figsize=(8, 6), dpi=100)plt.imshow(wordcloud, interpolation='bilinear')plt.axis('off')plt.show()

确保你的 Pillow 库版本至少为 5.0.0,以避免出现 'ImageDraw' object has no attribute 'textbbox' 错误。

解决 Python 词云库 WordCloud 中出现的 'ImageDraw' object has no attribute 'textbbox' 错误

原文地址: https://www.cveoy.top/t/topic/fYUL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录