生成词云遇AttributeError:'ImageDraw'无'textbbox'属性如何解决?
词云生成报错:AttributeError: 'ImageDraw' object has no attribute 'textbbox'
问题描述
在文本挖掘项目中,完成新闻数据预处理后,使用WordCloud库生成词云时触发上述错误。
预处理代码
import pandas as pd import numpy as np import matplotlib.pyplot as plt from nltk.corpus import stopwords from nltk.stem import PorterStemmer from textblob import Word from wordcloud import WordCloud newsData = pd.read_csv("data.txt", sep= '\t', header=None, names=["Description", "Category", "Tags"],on_bad_lines='skip', engine='python' , encoding='utf-8') newsData['Description'] = newsData['Description'].apply(lambda x: " ".join(x.lower() for x in x.split())) newsData['Category'] = newsData['Category'].apply(lambda x: " ".join(x.lower() for x in x.split())) newsData['Tags'] = newsData['Tags'].apply(lambda x: " ".join(x.lower() for x in x.split())) # 停用词过滤 stop = stopwords.words('english') newsData['Description'] = newsData['Description'].apply(lambda x: " ".join (x for x in x.split() if x not in stop)) # 词干提取 st = PorterStemmer() newsData['Description'] = newsData['Description'].apply(lambda x: " ".join ([st.stem(word) for word in x.split()])) newsData['Category'] = newsData['Category'].apply(lambda x: " ".join ([st.stem(word) for word in x.split()])) newsData['Tags'] = newsData['Tags'].apply(lambda x: " ".join ([st.stem(word) for word in x.split()])) # 词形还原 newsData['Description'] = newsData['Description'].apply(lambda x: " ".join ([Word(word).lemmatize() for word in x.split()])) newsData['Category'] = newsData['Category'].apply(lambda x: " ".join ([Word(word).lemmatize() for word in x.split()])) newsData['Tags'] = newsData['Tags'].apply(lambda x: " ".join ([Word(word).lemmatize() for word in x.split()])) culture = newsData[newsData['Category'] == 'culture'].sample(n=200) health = newsData[newsData['Category'] == 'health'].sample(n=200) dataSample = pd.concat([culture, health],axis=0) culturesmpl = culture[culture['Category'] == 'culture'].sample(n=200) healthspml = health[health['Category'] == 'health'].sample(n=200) cultureSTR = culturesmpl.Description.str.cat() healthSTR = healthspml.Description.str.cat()
词云生成代码
wordcloud_culture = WordCloud(collocations= False, background_color='white' ).generate(cultureSTR) # 绘图 plt.imshow(wordcloud_culture, interpolation='bilinear') plt.axis('off') plt.show()
报错信息
File ~/anaconda3/lib/python3.9/site-packages/wordcloud/wordcloud.py:508 in generate_from_frequencies box_size = draw.textbbox((0, 0), word, font=transposed_font, anchor="lt") AttributeError: 'ImageDraw' object has no attribute 'textbbox'
解决方案
这个错误的核心原因是WordCloud版本与Pillow版本不兼容:textbbox是Pillow 8.0.0及以上版本才新增的方法,当前使用的WordCloud新版本依赖这个方法,但你的Pillow版本低于8.0.0。
有两种解决方法:
- 升级Pillow到8.0.0以上版本
在终端执行命令:pip install --upgrade pillow>=8.0.0 - 降级WordCloud到兼容旧版Pillow的版本
如果不想升级Pillow,可以把WordCloud降级到1.8.1及以下版本,这个版本仍使用旧的textsize方法而非textbbox:pip install wordcloud<=1.8.1
执行完上述任一操作后,重新运行词云生成代码即可解决问题。
内容的提问来源于stack exchange,提问作者Sandra Moon
相关产品推荐
相关产品推荐

