代码地址如下:
http://www.demodashi.com/demo/14233.html
详细说明:
“词云”就是数据可视化的一种形式,给出一段文本,根据文本中词语的出现频率而生成的一幅图像,从而过滤掉大量的文本信息,人们只要扫一眼就能够明白文章主旨,使得数据分析的结果更加直观。
准备工作:
1.安装必要的第三方库:
pip install wordcloud
pip install jieba
pip install numpy
pip install wxPython
安装PIL,在以下地址下载PIL库进行安装:
http://effbot.org/media/downloads/PIL-1.1.7.win32-py2.7.exe
(或在http://effbot.org/downloads/ 中找到与你操作系统及python版本相对应
版本的PIL)
需要注意一点,因为wordcloud自带的字体文件不支持中文,为了让wordcloud支持中文词云的生成,安装完wordcloud库后需要hack一下,具体做法如下:
复制一个中文字体文件(在本项目中为方正姚体 FZYTK.TTF)到wordcloud安装路径下(如:C:\Python27\Lib\site-packages\wordcloud),然后打开wordcloud库中的wordcloud.py文档,将其中的
"FONT_PATH = os.environ.get('FONT_PATH', os.path.join(FILE, 'DroidSansMono.ttf'))"
(本项目的附件中将附带 FZYTK.TTF 字体文件)
改写为
"FONT_PATH = os.environ.get('FONT_PATH', os.path.join(FILE, 'FZYTK.TTF'))".
这样wordcloud将会以"FZYTK.TTF"作为字体文件.
项目结构:
整体的项目结构十分简单,一共三个脚本文件,一个是GUI界面脚本(draw_gui.py),
一个是GUI菜单的辅助性脚本(utility_template.py),
一个是词云生成器脚本(wordcloud_gen.py)。
如下:
程序实现
以下是程序的实现思路,以及步骤,实现步骤里,附上了关键代码,全部的代码,请下载代码后阅读
- 在wordcloud_gen.py中导入相关的库:
from os import path
from PIL import Image
import numpy as np
import time
from wordcloud import WordCloud, STOPWORDS
import jieba
- 编写wordcloud_gen.py中的相关函数,
读取传入文档:
def get_text(fn):
text = open(fn).read()
return text
中文分词:
def get_text_cn(fn):
t0 = get_text(fn)
t0 = jieba.cut(t0,cut_all = False)
text = " ".join(t0)
return text
生成词云:
def draw_wc(text,mask_path,stopwords):
mask = np.array(Image.open(mask_path))
wc = WordCloud(max_words = 1000,mask = mask,stopwords = stopwords,
margin = 0,random_state=1).generate(text)
im = wc.to_image()
im.show()
fn = str(int(time.time()))+'.jpg'
im.save(fn)
return im
3.在draw_gui.py中编写用户界面:
导入相关的库:
import wx
import os
from os import path
from collections import namedtuple
import wx.lib.rcsizer as rcs
from wordcloud import STOPWORDS
from utility_template import layout_template #自定义的库
import wordcloud_gen as wcg #自定义的库
编写界面:
class MainWindow(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title=title,size=(600,-1))
Size = namedtuple("Size",['x','y'])
s = Size(100,50)
self.cn_text = None
self.en_text = None
cwd = os.getcwd()
self.mask_path = path.join(path.abspath(cwd),'alice_mask.png')
self.user_sw = STOPWORDS
self.lt = layout_template()
self.name = 'WordCloud draw'
self.version = '0.2'
self.des = '''Draw the word cloud.\n'''
self.git_website = "https://github.com/WellenWoo/WordCloud_draw"
self.copyright = "(C) 2018 All Right Reserved"
"""创建菜单栏"""
filemenu = wx.Menu()
menuExit = filemenu.Append(wx.ID_EXIT,"E&xit\tCtrl+Q","Tenminate the program")
confmenu = wx.Menu()
menuSw = confmenu.Append(wx.ID_ANY,"StopWords","Add user StopWrods dict")
menuMask = confmenu.Append(wx.ID_ANY,"Mask","Set mask")
helpmenu = wx.Menu ()
menuAbout = helpmenu.Append(wx.ID_ABOUT ,"&About","Information about this program")
menuBar = wx.MenuBar ()
menuBar.Append(filemenu,"&File")
menuBar.Append(confmenu,"&Configure")
menuBar.Append(helpmenu,"&Help")
self.SetMenuBar(menuBar)
"""创建输入框"""
self.in1 = wx.TextCtrl(self,-1,size = (2*s.x,s.y))
"""创建按钮"""
b1 = wx.Button(self,-1,'text')
b2 = wx.Button(self, -1, "run")
"""设置输入框的提示信息"""
self.in1.SetToolTipString('choose a text file')
"""界面布局"""
self.sizer0 = rcs.RowColSizer()
self.sizer0.Add(b1,row = 1,col = 1)
self.sizer0.Add(self.in1,row = 1,col = 2)
self.sizer0.Add(b2,row = 1,col = 3)
"""绑定回调函数"""
self.Bind(wx.EVT_BUTTON, self.choose_cn, b1)
self.Bind(wx.EVT_BUTTON, self.draw_cn, b2)
'''菜单绑定函数'''
self.Bind(wx.EVT_MENU,self.OnExit,menuExit)
self.Bind(wx.EVT_MENU,self.OnAbout,menuAbout)
self.Bind(wx.EVT_MENU,self.get_stopwords,menuSw)
self.Bind(wx.EVT_MENU,self.get_mask,menuMask)
self.SetSizer(self.sizer0)
self.SetAutoLayout(1)
self.sizer0.Fit(self)
self.CreateStatusBar()
self.Show(True)
编写控件的回调函数:
def choose_cn(self,evt):
"""Choose a Chinses text file"""
self.cn_text = None
self.cn_text = self.choose_file(txtformat)
if self.cn_text is None:
pass
else:
self.in1.Clear()
self.in1.write(self.cn_text)
def choose_file(self,wildcard):
'''choose img'''
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
paths = dlg.GetPaths()
dlg.Destroy()
return paths[0]
else:
return None
def draw_cn(self,evt):
if self.cn_text is None:
self.raise_msg(u'plaese Choose a Chinses text file first.')
return None
else:
text = wcg.get_text_cn(self.cn_text)
wcg.draw_wc(text,self.mask_path,self.user_sw)
(英文文档即是程序代码文档本身)Python 实现的、带GUI界面的词云生成器
代码地址如下:
http://www.demodashi.com/demo/14233.html
注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权