1.打开cmd安装jieba库和 matplotlib。
2.打开python,输入代码。代码如下:
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
def create_word_cloud(filename):
text = open("孙子兵法.txt","r",encoding='GBK').read() #打开自己想要的文本
wordlist = jieba.cut(text, cut_all=True) # 结巴分词
wl = " ".join(wordlist)
wc = WordCloud( #设置词云
background_color="white", # 设置背景颜色
max_words=50, # 设置最大显示的词云数
font_path='C:/Windows/Fonts/simfang.ttf', # 索引在C盘上的字体库
height=1000,
width=1000,
max_font_size=150, # 设置字体最大值
random_state=150, # 设置有多少种随机生成状态,即有多少种配色方案
)
myword = wc.generate(wl) # 生成词云
plt.imshow(myword) # 展示词云图
plt.axis("off")
plt.show()
wc.to_file('img_book.png') # 把词云保存下
txt=open("孙子兵法.txt","r",encoding='GBK').read() #打开自己想要的文本
words=jieba.lcut(txt)
counts={}
for word in words:
if len(word)==1: #排除单个字符的分词结果
continue
else :
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(20):
word,count=items[i]
print ("{0:<20}{1:>5}".format(word,count))
if __name__ == '__main__':
create_word_cloud('孙子兵法') #运行编辑的函数,获得词云
3.结果与词云效果图