python实现词云效果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37886429/article/details/85391385

一、说明

wordcloud是Python中的一个小巧的词云生成器。绘制图片是也通过第三方模块 pillow和matplotlib 实现的,因此需要安装matplotlib和wordcloud模块

pip install wordcloud
pip install matplotlib
pip install jieba   #识别中文
pip install pillow  #图像处理

二、wordcloud中文识别

需要有识别中文的字体库,windows上面在 C:\Windows\Fonts 路径下,比较常用的有 宋体(simsun.ttc),黑体(simhei.ttf),楷体(simkai.ttf) 等。

三、示例代码块

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import matplotlib.pyplot as plt
from PIL import Image as image
import jieba  
import numpy
from wordcloud import WordCloud,ImageColorGenerator,STOPWORDS

def chinese_jieba(text):
    #通过jieba工具将中文文本做处理,并返回指定格式的内容
    wordlist_jieba = jieba.cut(text)
    text_jieba = ' '.join(wordlist_jieba)
    return text_jieba

def main(filename):
    with open(filename,'rb') as f:
        text = chinese_jieba(f.read().decode())
        
    mask_pic = numpy.array(image.open('test.jpg'))  #打开图像处理,设置遮罩层

    #设置固定的词个数为0
    # stopwords = {'黑娃':0,'白嘉轩':0}
    #也可以按照下面格式设置
    stopwords = set(STOPWORDS)
    stopwords = stopwords.union(set(['黑娃', '白嘉轩']))   #将不想在词云上出现的词,放入集合中,也就是设置固定词个数为0

    wordclod = WordCloud(
        background_color='white',  #设置背景颜色,默认是黑色
        margin=0,
        max_words=2000, #关键字的个数
        max_font_size=100, #字体大小
        font_path=r'C:\Windows\Fonts\simsun.ttc',  #设置中文识别
        mask=mask_pic,  #添加遮罩层,也就是设置词云形状
        stopwords = stopwords, #过滤固定的词
    ).generate(text)   #将text里面所有的词统计,产生词云

    # image_colors = ImageColorGenerator(mask_pic)

    plt.imshow(wordclod)
    # plt.imshow(wordclod.recolor(color_func=image_colors))
    plt.axis('off')
    plt.show()
    wordclod.to_file('bailuyuan.jpg')  #保存图片

if __name__ == "__main__":
    filename = '白鹿原.txt'
    main(filename)

备注:我是在网上找了白鹿原小说做的词云效果

四、效果图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/85391385