只需要输入txt文档所在路径,就可以输出词云图,词云图图形可自定义。
停用词库需要自己下载,作用是分词更准确。
mask遮罩图片需要自己搞一张,弄一张椭圆的图片,必须背景色是白色,那么词云图输出就是椭圆。
mask.png
代码
#coding=utf-8
#@Time : 2020/11/14 22:16
#@Author :java川
#@File : 词云图
#@Software: PyCharm
## 包的作用
import time
import jieba #分词
from wordcloud import WordCloud #词云
from PIL import Image #图片处理
import numpy as np #将图片变成数组
import collections #计数器
from matplotlib import pyplot as plt #绘图
def cut_word(text):
#分词:cut_all=False:精确模式 HMM=True:使用隐式马尔科夫
cut = jieba.cut(text,cut_all=False,HMM=True)
object_list = []
#读取停用词
with open("stop_word.txt", 'r', encoding='UTF-8') as meaninglessFile:
stopwords = set(meaninglessFile.read().split('\n'))
stopwords.add(' ')
#如果单词不在停用词里,则添加
for word in cut:
if word not in stopwords:
object_list.append(word)
#collections.Counter 计数器,统计单词个数
word_counts = collections.Counter(object_list)
print(word_counts)
return word_counts
#生成词云图保存
def get_cloud(word_counts):
#遮罩图:必须是白底的
img = Image.open('mask.png')
img_array = np.array(img) #将图片变为数组
wc = WordCloud(
background_color = 'white', # 背景颜色
mask = img_array, #遮罩图片
relative_scaling=0.3, #字体关联度
max_font_size = 40,
height=400,
width=1000,
max_words=150, #字体数量显示
font_path='msyh.ttc',#字体格式
)
wc.generate_from_frequencies(word_counts,150) #生成词云图
fig = plt.figure(1)
plt.imshow(wc) # 显示词云
plt.axis('off') # 关闭坐标
wc.to_file(r"C:\Users\MI\Desktop\词云图{}javachuan.png".format(str(int(time.time()))))
#调整边框
#plt.subplots_adjust(top=0.99, bottom=0.01, right=0.99, left=0.01, hspace=0, wspace=0)
#保存图片 plt 绘图保存 不高清
# plt.savefig(r'C:\Users\MI\Desktop\词云图{}javachuan.png'.format(str(int(time.time()))),dpi=600)
plt.show()
def main():
print("\n*********建议直接拖拽txt文档到黑框**********\n")
path = str(input("请输入 txt 文档路径:"))
try:
with open(path, 'r', encoding='UTF-8') as f:
text = f.read()
except:
print(" ---------------文档路径 {} 不存在!!!---------------- ".format(path))
main()
word_counts = cut_word(text)
get_cloud(word_counts)
if __name__ == '__main__':
main()
结果图: