python wordcloud库使用
时间: 2023-12-02 20:05:29 浏览: 57
Wordcloud是一个Python库,用于生成词云图。它可以通过文本数据来创建词云图,每个单词的大小根据它们在文本中出现的频率来调整。下面是使用Wordcloud库的一些常见用法:
1. 安装Wordcloud库:
```
pip install wordcloud
```
2. 导入Wordcloud库及其他必要的库:
```
import wordcloud
from wordcloud import WordCloud
import matplotlib.pyplot as plt
```
3. 准备文本数据:
```
text = "hello world hello python hello wordcloud"
```
4. 创建Wordcloud对象:
```
wordcloud = WordCloud(width=800, height=800, background_color='white', min_font_size=10).generate(text)
```
5. 生成词云图:
```
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
```
6. 根据文本数据的频率生成不同大小的单词:
```
wordcloud = WordCloud(width=800, height=800, background_color='white', min_font_size=10).generate_from_frequencies(frequencies)
```
7. 设置词云图的颜色:
```
wordcloud = WordCloud(width=800, height=800, background_color='white', min_font_size=10, colormap='Set2').generate(text)
```
8. 保存词云图:
```
wordcloud.to_file("wordcloud.png")
```
阅读全文