python词云图生成脚本

更多实用工具在这里点击

只需要输入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()

结果图:
在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值