生成所需形状的wordcloud?

时间:2017-10-26 16:44:42

标签: python matplotlib word-cloud

我试图在Python中创建一个我想要的形状的wordcloud,使用一个字数作为值的字典。为此我正在从网上读取一个图像。图像正确存储在变量中,但wordcloud未被渲染。但是使用默认形状,wordcloud会显示出来。以下是我的代码:

from PIL import Image
import urllib
import requests
img=Image.open(requests.get('https://internationalcriminallaw.files.wordpress.com/2013/04/terrorism.png', stream=True).raw)
motive=terror['Motive'].str.lower().str.replace(r'\|', ' ').str.cat(sep=' ')
words=nltk.tokenize.word_tokenize(motive)
word_dist = nltk.FreqDist(words)
stopwords = nltk.corpus.stopwords.words('english')
words_except_stop_dist = nltk.FreqDist(w for w in words if w not in stopwords) 
mask1=img
wordcloud = WordCloud(
                      stopwords=STOPWORDS,
                      background_color='white',
                      mask=mask1,
                      max_font_size=40
                     )
wordcloud.generate(" ".join(words_except_stop_dist))
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

以下是错误:

AttributeError Traceback (most recent call last)
<ipython-input-147-6aabda55c848> in <module>()
  6                           max_font_size=40
  7                          )
----> 8 wordcloud.generate(" ".join(words_except_stop_dist))
  9 plt.imshow(wordcloud)
 10 plt.axis('off')

/home/austin/anaconda3/lib/python3.5/site-packages/wordcloud/wordcloud.py in generate(self, text)
448         self
449         """
--> 450         return self.generate_from_text(text)
451 
452     def _check_generated(self):

/home/austin/anaconda3/lib/python3.5/site-packages/wordcloud/wordcloud.py in generate_from_text(self, text)
434         """
435         words = self.process_text(text)
--> 436         self.generate_from_frequencies(words)
437         return self
438 

    /home/austin/anaconda3/lib/python3.5/site-packages/wordcloud/wordcloud.py in generate_from_frequencies(self, frequencies)
281         if self.mask is not None:
282             mask = self.mask
--> 283             width = mask.shape[1]
284             height = mask.shape[0]
285             if mask.dtype.kind == 'f':

/home/austin/anaconda3/lib/python3.5/site-packages/PIL/Image.py in __getattr__(self, name)
625             new['version'] = 3
626             return new
--> 627         raise AttributeError(name)
628 
629     def __getstate__(self):

AttributeError: shape

我该怎么办?

0 个答案:

没有答案