python 基于 wordcloud + jieba + matplotlib 生成詞云

詞云##

image

詞云是啥?詞云突出一個(gè)數(shù)據(jù)可視化,酷炫。以前以為很復(fù)雜,不想python已經(jīng)有成熟的工具來(lái)做詞云。而我們要做的就是準(zhǔn)備關(guān)鍵詞數(shù)據(jù),挑一款字體,挑一張模板圖片,非常非常無(wú)腦。準(zhǔn)備好了嗎,快跟我一起動(dòng)手吧

模塊##

本案例基于python3.6, 相關(guān)模塊如下,安裝都是直接 pip install <模塊名>

  1. wordcloud 作用如其名。本例核心模塊,它把我們帶權(quán)重的關(guān)鍵詞渲染成詞云
  2. matplotlib 繪圖模塊,主要作用是把wordcloud生成的圖片繪制出來(lái)并在窗口展示
  3. numpy 圖像處理模塊,讀取圖片生成像素矩陣
  4. PIL (pip install pillow) 圖片處理模塊, 打開(kāi)初始化圖片
  5. jieba 牛逼的分詞模塊,因?yàn)槲沂菑囊粋€(gè)txt文本里提取關(guān)鍵詞,所以需要 jieba 來(lái)分詞并統(tǒng)計(jì)詞頻。如果是已經(jīng)有了現(xiàn)成的數(shù)據(jù),不再需要它

代碼##

# -*- coding=utf8 -*-
import matplotlib.pyplot as plt
import jieba.analyse
import numpy
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator

def readTxt(file, encoding='utf8'):
    """
    :param file:
    :param encoding:
    :return:
    """
    with open(txt_file, 'r', encoding='utf16') as f:
        txt = f.read()
    return txt

def textDict(content):
    """
    jieba 提取1000個(gè)關(guān)鍵詞及其比重
    :param content:
    :return:
    """
    result = jieba.analyse.textrank(content, topK=1000, withWeight=True)
    # 轉(zhuǎn)化為比重字典
    keywords = dict()
    for i in result:
        keywords[i[0]] = i[1]
    return keywords

def renderWordCloud(keywords, sourceImg):
    # 獲取圖片資源
    image = Image.open(sourceImg)
    # 轉(zhuǎn)為像素矩陣
    graph = numpy.array(image)

    # wordcloud 默認(rèn)字體庫(kù)不支持中文,這里自己選取中文字體
    fontPath = 'C:/Windows/Fonts/SIMLI.TTF'
    #fontPath = 'C:/Windows/Fonts/mplus-1mn-regular.ttf'
    wc = WordCloud(
        font_path=fontPath,
        background_color='white',
        max_words=1000,
        # 使用的詞云模板背景
        mask=graph
    )
    # 基于關(guān)鍵詞信息生成詞云
    wc.generate_from_frequencies(keywords)
    # 讀取模板圖片的顏色
    image_color = ImageColorGenerator(graph)
    # 生成詞云圖
    plt.imshow(wc)
    # 用模板圖片的顏色覆蓋
    plt.imshow(wc.recolor(color_func=image_color))
    # 關(guān)閉圖像坐標(biāo)系
    plt.axis('off')
    # 顯示圖片--在窗口顯示
    plt.show()


txt_file = 'C:/Users/KF/Downloads/《圍城》錢(qián)鐘書(shū)(完美版).TXT'
source_img = 'C:/Users/KF/Pictures/ul1241-2001.jpg'
#source_img = 'C:/Users/KF/Pictures/微信圖片_20170710102042.jpg'
#source_img = 'C:/Users/KF/Pictures/微信圖片_20170710102054.jpg'
#source_img = 'E:\DOC\Carl\wallpapers\d250038c4fde4ea7f36ebe010a7b58ca.jpg'

content = readTxt(txt_file)
keywords = textDict(content)
renderWordCloud(keywords, source_img)

成果##

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容