词云代码
时间: 2023-07-03 15:25:14 浏览: 38
以下是 Python 中生成词云的代码示例:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 过滤停用词
stopwords = set(['的', '了', '是', '我', '你', '他', '她', '我们', '你们', '他们', '她们'])
filtered_words = [word for word in words if word not in stopwords]
# 统计词频
word_counts = {}
for word in filtered_words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 生成词云
wc = WordCloud(width=800, height=600, background_color='white', font_path='msyh.ttc')
wc.generate_from_frequencies(word_counts)
# 显示词云
plt.imshow(wc)
plt.axis('off')
plt.show()
```
其中,`text.txt` 是文本文件的路径,`msyh.ttc` 是字体文件的路径,可以替换成其他字体文件。如果需要更多的自定义设置,可以查看 WordCloud 的文档。