wordcloud库生成词云的方法
时间: 2023-09-27 16:05:51 浏览: 45
wordcloud库是一个Python的词云生成库,可以通过以下步骤生成词云:
1. 安装wordcloud库:在命令行中使用pip命令安装,如下所示:`pip install wordcloud`
2. 导入所需的库和文件:导入wordcloud库和需要生成词云的文本文件。
```python
import wordcloud
from wordcloud import WordCloud
text = open('text.txt').read()
```
3. 创建WordCloud对象:设置WordCloud对象的参数,如图片大小、字体、背景颜色等。
```python
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,
min_font_size = 10).generate(text)
```
4. 生成词云:调用WordCloud对象的generate()方法生成词云,并保存到本地。
```python
wordcloud.to_file("wordcloud.png")
```
完整代码示例:
```python
import wordcloud
from wordcloud import WordCloud
# 读取文本文件
text = open('text.txt').read()
# 设置停用词
stopwords = set(['the', 'and', 'of', 'in', 'to', 'a', 'an', 'that', 'is', 'for', 'with'])
# 创建WordCloud对象
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,
min_font_size = 10).generate(text)
# 生成词云并保存到本地
wordcloud.to_file("wordcloud.png")
```