python词云 小说《庆余年》

一、概述

使用jieba分词和wordcloud生产 小说的词云库

源码地址:https://github.com/jw-star/pythonDemo/tree/master/%E5%BA%86%E4%BD%99%E5%B9%B4wordcloud

二、效果图

在这里插入图片描述

三、流程

#coding=utf-8
import jieba
from wordcloud import WordCloud
import os
import numpy
import PIL.Image as Image
cur_path=os.path.dirname(__file__)  #当前路径
mask_pic = numpy.array(Image.open(os.path.join(cur_path, 'aa.jpg'))) #图片原型
1、分词方法
#分词
def myjieba(txt) : 
    jieba.add_word('范若若')  #词库添加自定义内容
    jieba.add_word('林婉儿')
    jieba.add_word('长公主')
    wordlist=jieba.cut(txt)
    return " ".join(wordlist)
2、获取中文停用词库(排除无用词)
def get_stopwords():
    #获取停用词的路径
    dir_name_path=os.path.join(cur_path, '停用词库.txt') #可以向词库添加不需要的词,完善图片效果
    #创建set集合来保存停用词
    stopwords = set()
    with open(dir_name_path, 'r', encoding='utf-8') as f:
        text=f.read()
        textlist = text.split('\n')
        #print(textlist)
        return textlist
3、词云设置并生成图片
with open(os.path.join(cur_path, '庆余年.txt'), encoding='utf-8') as fp:
    txt=fp.read()
    txt=myjieba(txt)
    wordcloud = WordCloud(font_path = 'C:\Windows\Fonts\simkai.TTF',
                            background_color = 'white', # 背景色
                             max_words = 120, # 最大显示单词数
                             max_font_size = 66, # 频率最大单词字体大小
                             scale=6,#图片清晰度,不要调太高,否则云图加载不出来
                             stopwords = get_stopwords(), # 过滤停用词
                                mask=mask_pic
                           ).generate(txt)
    image = wordcloud.to_image()
    image.show()
    #两种输出图片方式
    # 1、指定精度进行输出
    # plt.savefig("E:/temp.jpg",dpi=600)
    # 2、完整图片输出
    wordcloud.to_file(cur_path+"temp.png")
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值