绘制词云
时间: 2023-09-13 18:12:26 浏览: 44
绘制词云需要使用一些第三方库,比如`wordcloud`和`matplotlib`。先确保你已经安装了这些库。
下面是一个简单的例子,展示如何从文本中提取关键词并绘制词云:
```python
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 定义词云参数
wordcloud = WordCloud(width=800, height=800,
background_color='white',
stopwords=set(['the', 'and', 'in', 'for', 'that', 'was']),
min_font_size=10).generate(text)
# 绘制词云
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
```
这个例子中,我们从一个文本文件`input.txt`中读取内容,然后使用`WordCloud`类定义了词云的一些参数,比如宽、高、背景颜色、停用词等。然后我们使用`generate`方法从文本中提取关键词,并生成词云图像。最后使用`matplotlib`库绘制词云。