import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
txt = open("三体节选.txt",'r',encoding='utf-8').read()
words =jieba.lcut(txt) #使用 jieba 库函数分词
counts={}
for word in words:
if len(word) == 1: #排除长度为 1 的字符分词结果
continue
else:
counts[word]=counts.get(word,0)+1 #新词需要先新建,所以用 get 方法
items = list(counts.items()) #将字典中的键值对转为元组
items.sort(key=lambda x:x[1],reverse=True)#按照统计结果降序排序
ciyun =[]
for i in range(50):
word,count = items[i]
print(word,count)
ciyun.append(word)
text_cut =''.join(ciyun) #转为字符串,并用空格分隔
wordscloud =WordCloud(background_color='white',font_path ='汉仪乐喵体.ttf',width=1000,height=1000,margin=2).generate(text_cut)
wordscloud.to_file("词云.png")
plt.imshow(wordscloud)
plt.axis('off') #关闭坐标轴
plt.show()
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com