‘ImageDraw’对象没有’textbbox’属性。

huangapple go评论62阅读模式
英文:

'ImageDraw' object has no attribute 'textbbox'

问题

I am working on a simple text mining project. When I tried to create a word-cloud I got this error:

AttributeError: 'ImageDraw' object has no attribute 'textbbox'

I have a dataset of News and their categories; to create a word-cloud I tried to preprocessing the text:

import pandas as pd
import numpy as np
import pandas as pd
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()))

# stopword filtering
stop = stopwords.words('english')
newsData['Description'] =  newsData['Description'].apply(lambda x: " ".join (x for x in x.split() if x not in stop))
#stemming

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()]))

#lemmatize

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()

and then I tried to create a wordcloud using WordCloud library

wordcloud_culture =  WordCloud(collocations= False, background_color='white' ).generate(cultureSTR)

# Plot
plt.imshow(wordcloud_culture, interpolation='bilinear')
plt.axis('off')
plt.show()

but after running this code I got the error:

  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'

Do you know how can I fix this?

英文:

I am working on a simple text mining project. When I tried to create a word-cloud I got this error:

AttributeError: 'ImageDraw' object has no attribute 'textbbox'

I have a dataset of News and their categories; to create a word-cloud I tried to preprocessing the text:


import pandas as pd
import numpy as np
import pandas as pd
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')
#print(newsData.head())
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()))
# stopword filtering
stop = stopwords.words('english')
newsData['Description'] =  newsData['Description'].apply(lambda x: " ".join (x for x in x.split() if x not in stop))
#stemming
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()]))
#lemmatize
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()]))
#print(newsData.head())
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)
#print(dataSample.head())
cultureSTR = culturesmpl.Description.str.cat()
healthSTR = healthspml.Description.str.cat()
#print(spam_str)

and then I tried to create wordcloud using WordCloud library

wordcloud_culture =  WordCloud(collocations= False, background_color='white' ).generate(cultureSTR)
# Plot
plt.imshow(wordcloud_culture, interpolation='bilinear')
plt.axis('off')
plt.show()

but after running this code I got the error:

  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'

do you know how can I fix this?

答案1

得分: 5

历史

ImageDraw.textsize() 方法在PIL版本9.2.0中被弃用,并且从2023年7月1日起,在版本10.0.0中完全移除

ImageDraw.textbbox() 方法在版本8.0.0中被引入,作为一个更健壮的解决方案。

示例

如果你只是想简单地替换一行代码,之前你可能有:

text_width, text_height = ImageDraw.Draw(image).textsize(your_text, font=your_font)

..那么你可以改用:

_, _, text_width, text_height = ImageDraw.Draw(image).textbbox((0, 0), your_text, font=your_font)

解释

textsize() 输出文本的名义宽度和高度作为一个元组:(宽度, 高度)
textbbox() 输出边界框的x和y范围作为一个元组:(左, 上, 右, 底)

_, _,开头是丢弃输出元组的前两个元素的一种方式。

textbbox()中添加(0, 0)作为第一个参数告诉它将边界框锚定在原点。

避免依赖过时的库,探索这一变化的原因以及为什么textbbox()是一个更健壮的方法!

英文:

History

The ImageDraw.textsize() method was deprecated in PIL version 9.2.0 and completely removed beginning with version 10.0.0 on 2023-07-01.

The ImageDraw.textbbox() method was introduced in version 8.0.0 as a more robust solution.

Example

If you are looking to simply replace one line of code, and you previously had

text_width, text_height = ImageDraw.Draw(image).textsize(your_text, font=your_font)

..then you could instead use

_, _, text_width, text_height = ImageDraw.Draw(image).textbbox((0, 0), your_text, font=your_font)

Explanation

textsize() outputs dimensions for the nominal width and height of the text as a tuple: (width, height).
textbbox() outputs the x and y extents of the bounding box as a tuple: (left, top, right, bottom).

Starting the line with _, _, is a way to discard the first two elements of the output tuple.

Adding (0, 0) as the first argument in textbbox() tells it to anchor the bounding box at the origin.

Avoid relying on outdated libraries, and explore reasons for this change and why textbbox() is a more robust method!

答案2

得分: 2

"textsize"函数在Pillow 10中已被弃用。

因此,安装Pillow 9.5.0将解决此问题:

pip3 install Pillow==9.5.0
英文:

The textsize function is deprecated in Pillow 10.

Thus installing Pillow 9.5.0 will fix the issue:

pip3 install Pillow==9.5.0

答案3

得分: 0

我安装了Pillow 7.1.1,然后升级到了9.5.0。然后错误消失了!

所以如果你面临相同的问题,可以使用以下命令修复:

python3 -m pip install --upgrade Pillow
英文:

I was installed pillow 7.1.1, then I upgrade it to 9.5.0. and then the error was gone!

so if you face the same problem you can fix with:

python3 -m pip install --upgrade Pillow

huangapple
  • 本文由 发表于 2023年5月7日 00:08:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定