python词云如何设置停用词
时间: 2023-10-13 07:05:48 浏览: 142
对于设置停用词,可以使用Python中的第三方库jieba和wordcloud来实现。具体步骤如下:
1. 安装jieba和wordcloud库:
```python
!pip install jieba
!pip install wordcloud
```
2. 导入库和数据:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
text = '这是一段需要生成词云的文本'
```
3. 使用jieba进行中文分词和去除停用词:
```python
words = jieba.cut(text)
text_without_stopwords = []
# 去除停用词
with open('stopwords.txt', 'r', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
for word in words:
if word not in stopwords:
text_without_stopwords.append(word)
text_without_stopwords = ' '.join(text_without_stopwords) # 将列表转化为字符串,词之间用空格分隔
```
其中stopwords.txt是一个包含停用词的文本文件,每个停用词占一行。
4. 生成词云:
```python
wordcloud = WordCloud(font_path='simhei.ttf', background_color='white').generate(text_without_stopwords)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
其中font_path是设置字体路径,background_color是设置背景颜色,interpolation是设置插值方法,axis是控制坐标轴是否显示。最后执行即可生成词云图。
阅读全文
相关推荐















