应用wordcloud库,根据文本生成词云图
时间: 2023-12-14 08:05:40 浏览: 29
好的,首先需要安装 wordcloud 库。您可以使用以下命令在命令行中安装:
```
pip install wordcloud
```
安装完成后,您可以使用以下代码生成词云图:
```python
import matplotlib.pyplot as plt
from wordcloud import WordCloud
text = "in the Olympic Peninsula of northwest Washington State, a town named Forks exists under constant cover of clouds. It rains on this inconsequential town more than any other place in the United States of America. It was from this town and its gloomy, omnipresent shade that my mother escaped with me when I was only a few months old."
# 生成词云图
wordcloud = WordCloud(width=800, height=800, background_color='white').generate(text)
# 显示生成的词云图
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.tight_layout(pad=0)
plt.show()
```
在这个示例中,我们使用了 `WordCloud` 类生成词云图,并指定了词云图的宽度、高度和背景颜色。我们还将 `generate()` 方法应用于文本,以生成词云图。最后,我们使用 `imshow()` 方法显示生成的词云图。