python利用wordcloud库,生成《红楼梦》中出现最多的20个2字词汇(词长为2)的词云图
时间: 2024-02-15 13:03:12 浏览: 23
好的,下面是实现的代码,注释中有详细的说明:
```python
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取红楼梦文本文件
with open('hongloumeng.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词对文本进行切分
words = jieba.cut(text)
# 统计2字词汇出现次数
counts = Counter()
for word in words:
if len(word) == 2:
counts[word] += 1
# 输出出现次数最多的20个2字词汇
top20 = sorted(counts.items(), key=lambda x: x[1], reverse=True)[:20]
for word, count in top20:
print(word, count)
# 生成2字词汇出现次数词云
wordcloud = WordCloud(font_path='msyh.ttc').generate_from_frequencies(counts)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
```
在上面的代码中,我们使用了jieba库对文本进行了分词,然后遍历分词结果,统计出现次数为2的词汇并计数。接着,我们输出了出现次数最多的20个2字词汇,然后使用WordCloud库生成了这些词汇出现次数的词云图。
注:在运行代码前需要提前安装jieba, collections, wordcloud, matplotlib等相关库。