詞云##
image
詞云是啥住涉?詞云突出一個數(shù)據(jù)可視化,酷炫钠绍。以前以為很復(fù)雜舆声,不想python已經(jīng)有成熟的工具來做詞云。而我們要做的就是準(zhǔn)備關(guān)鍵詞數(shù)據(jù)柳爽,挑一款字體媳握,挑一張模板圖片,非常非常無腦磷脯。準(zhǔn)備好了嗎蛾找,快跟我一起動手吧
模塊##
本案例基于python3.6, 相關(guān)模塊如下赵誓,安裝都是直接 pip install <模塊名>
:
- wordcloud 作用如其名打毛。本例核心模塊柿赊,它把我們帶權(quán)重的關(guān)鍵詞渲染成詞云
- matplotlib 繪圖模塊,主要作用是把wordcloud生成的圖片繪制出來并在窗口展示
- numpy 圖像處理模塊幻枉,讀取圖片生成像素矩陣
- PIL (pip install pillow) 圖片處理模塊碰声, 打開初始化圖片
- jieba 牛逼的分詞模塊,因?yàn)槲沂菑囊粋€txt文本里提取關(guān)鍵詞熬甫,所以需要 jieba 來分詞并統(tǒng)計詞頻胰挑。如果是已經(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個關(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)字體庫不支持中文椿肩,這里自己選取中文字體
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/《圍城》錢鐘書(完美版).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