WordCloudCreator

来源:互联网 发布:淘宝里要验证码充流量 编辑:程序博客网 时间:2024/06/05 02:05

今天终于完整地做好了人生的第一个小软件~!

用python写的,基于jieba包的,带有UI的词云制作小软件:WordCloudCreator

虽然很简单,但是作为新手非常辛苦地踩了无数的坑,也在过去的一个月里牺牲了无数业余时间。不过这段时间里收获了很多,看着小软件也特别有成就感。

源代码就放在下面啦,写的很幼稚,希望能得到一些批评意见。

环境是win32,python2.7

主程序:

import syssys.setdefaultencoding('utf-8')import matplotlib.pyplot as pltfrom wordcloud import WordCloud,STOPWORDS,ImageColorGeneratorimport jiebafrom scipy.misc import imreadfrom os import pathimport osos.system('cls')import jieba.analyse as analyseimport ioimport shutilfrom PIL import ImageFontimport timeimport Tkinter as tkfrom Tkinter import *import tkFileDialogimport FileDialogimport tkMessageBox as messageimport tkColorChooserimport ttkimport tkFontclass Window:    def __init__(self, status, width=360, height=680):        self.status = status        self.w = width        self.h = height        self.root = tk.Tk()        self.root.title("词云制作 Beta")                self.filedict = {        # main key: text, stopword, mask, wordcloud, tagFile, useDictPath, addWord, delWord                                     # second key: path, tkPath, content            'text':{'path':'','tkPath':'','content':''}            , 'stopword':{'path':'','tkPath':'','content':''}            , 'mask':{'path':'','tkPath':'','content':''}            , 'wordcloud':{'path':'','tkPath':'','content':''}            , 'tagFile':{'path':'','tkPath':'','content':''}            , 'useDictPath':{'path':'','tkPath':'','content':''}            , 'addWord':{'path':'','tkPath':'','tkcontent':''}            , 'delWord':{'path':'','tkPath':'','tkcontent':''}            }                for filetype in ['text', 'stopword', 'mask', 'wordcloud', 'tagFile', 'useDictPath', 'addWord', 'delWord']:            self.filedict[filetype]['tkPath']=StringVar()        self.filedict['addWord']['tkcontent']=StringVar()        self.filedict['delWord']['tkcontent']=StringVar()                    self.Chinese=IntVar()        self.keywords=IntVar()        self.userDict=IntVar()        self.addDict=IntVar()        self.delDict=IntVar()        self.cutMode=IntVar()        self.colorMode=IntVar()                self.canvas_w=IntVar()        self.canvas_h=IntVar()        self.margin=IntVar()        self.background_color=StringVar()        self.font=StringVar()        self.max_font_size=IntVar()        self.max_words=IntVar()        self.random_state=IntVar()        self.Chinese.set(1)        self.cutMode.set(1)        self.colorMode.set(1)        self.canvas_w.set(1200)        self.canvas_h.set(1600)        self.margin.set(10)        self.background_color.set("#ffffff")        self.font.set("simhei.ttf")        self.max_font_size.set(70)        self.max_words.set(100)        self.random_state.set(100)        self.myWordCloudArgu = {            'textpath':''          , 'stopwordpath':''          , 'maskpath':''          , 'savepath':''          , 'Chinese':''          , 'keywords': ''          , 'tagFile':  ''          , 'userDict':''          , 'userDictPath':''          , 'addDict':''          , 'addWord':''          , 'delDict':''          , 'delWord':''          , 'cutMode':''          , 'colorMode':''          , 'canvas_w':''          , 'canvas_h' : ''          , 'margin':''          , 'background_color':''          , 'font':''          , 'max_font_size':''          , 'max_words':''          , 'random_state':''          }        self.loop()    def raw(self,text):        escape_dict={'\a':r'\a',               '\b':r'\b',               '\c':r'\c',               '\f':r'\f',               '\n':r'\n',               '\r':r'\r',               '\t':r'\t',               '\v':r'\v',               '\'':r'\'',               '\"':r'\"',               '\0':r'\0',               '\1':r'\1',               '\2':r'\2',               '\3':r'\3',               '\4':r'\4',               '\5':r'\5',               '\6':r'\6',               '\7':r'\7',               '\8':r'\8',               '\9':r'\9'}        """Returns a raw string representation of text"""        new_string='r"'        for char in text:            try: new_string+=escape_dict[char]            except KeyError: new_string+=char        new_string+='"'        return new_string        def getKeyWords(self):        if len(self.myWordCloudArgu['textpath'])>0 and self.myWordCloudArgu['keywords']:            print 'myWordCloudArgu[textpath]: ' , self.myWordCloudArgu['textpath']            print 'keywords', self.myWordCloudArgu['keywords']            text = open(path.normpath(self.myWordCloudArgu['textpath'])).read()            keywords = analyse.extract_tags(text,50, withWeight=False)            keywordList=[]            for word in keywords : #unicode type                keywordList.append(word) # transfer unicode into chinese            keywordtext = " ".join(keywordList)            f = open(path.normpath(self.myWordCloudArgu['tagFile']), 'w').write(str(keywordtext))            #f = codecs.open(os.path.join(path,'key.txt'), 'w','utf-8').write(str(keywordtext))    def getUserDict(self):        if len(self.myWordCloudArgu['textpath'])>0 and self.myWordCloudArgu['userDict']:            userDict = jieba.load_userdict(path.normpath(self.myWordCloudArgu['userDictPath']))    def add2Dict(self):        if len(self.raw(self.myWordCloudArgu['textpath']))>0 and self.myWordCloudArgu['addDict']:            jieba.add_word(self.myWordCloudArgu['addWord'])    def delfromDict(self):        if len(self.raw(self.myWordCloudArgu['textpath']))>0 and self.myWordCloudArgu['delDict']:            jieba.del_word(self.myWordCloudArgu['delWord'])    def createWordCloud(self):        print "**************drawing word cloud**************"                if len(self.myWordCloudArgu['textpath'])>0:            wc_mask = imread(path.normpath(self.myWordCloudArgu['maskpath']))            text = open(path.normpath(self.myWordCloudArgu['textpath'])).read()            stopwords = open(path.normpath(self.myWordCloudArgu['stopwordpath'])).read()            my_wordcloud = WordCloud(                width=self.myWordCloudArgu['canvas_w'],                height=self.myWordCloudArgu['canvas_h'],                margin = self.myWordCloudArgu['margin'],                background_color=self.myWordCloudArgu['background_color'],                font_path = self.myWordCloudArgu['font'],                 max_font_size=self.myWordCloudArgu['max_font_size'],                max_words=self.myWordCloudArgu['max_words'],                mask = wc_mask,                random_state = self.myWordCloudArgu['random_state'],                stopwords = stopwords                )                        if self.myWordCloudArgu['Chinese']:                stopwordsGenerator = jieba.cut(str(stopwords)) #change structure                stopwordsList = [word for word in stopwordsGenerator]                            if self.myWordCloudArgu['cutMode'] == 2 :                     wordlist_after_jieba = jieba.cut(str(text),cut_all=True) # full mode                elif self.myWordCloudArgu['cutMode'] == 3 :                    wordlist_after_jieba = jieba.cut_for_search(str(text))  # search mode                else:                    wordlist_after_jieba = jieba.cut(str(text)) #default mode                wordlist_jieba = []                for word in wordlist_after_jieba : #unicode type                    chword = word #.encode('gbk')                    if chword not in stopwordsList:                        wordlist_jieba.append(chword) # transfer unicode into chinese                wl_space_split = " ".join(wordlist_jieba)                            my_wordcloud.generate(wl_space_split)            else:                my_wordcloud.generate()            if self.myWordCloudArgu['colorMode'] == 2:                                image_colors = ImageColorGenerator(wc_mask)                my_wordcloud.recolor(color_func=image_colors)            my_wordcloud.to_file(path.normpath(self.myWordCloudArgu['savepath']))                        plt.figure()              plt.imshow(my_wordcloud)            plt.axis("off")            plt.show()     def getFilePath(self,filetype): #get user defined path from button        print 'get file'        if filetype == 'mask':            self.filedict[filetype]['path'] = tkFileDialog.askopenfilename(                filetypes=[('JPEG', ('*.jpg','*.jpeg','*.jif','*.jfif')),('PNG', '*.png'),('BMP', '*.bmp'),('TIFF', ('*.tif','*.tiff')),('All files', '*.*')])        elif filetype == 'wordcloud':            self.filedict[filetype]['path'] = tkFileDialog.asksaveasfilename(defaultextension='*.png',filetypes=[('PNG', '*.png')])        elif filetype == 'tagFile':            self.filedict[filetype]['path'] = tkFileDialog.asksaveasfilename(defaultextension='*.txt',filetypes=[('text files', '*.txt'),('All files', '*.*')])        else:            self.filedict[filetype]['path'] = tkFileDialog.askopenfilename(filetypes=[('text files', '*.txt'),('All files', '*.*')])        filepath = self.filedict[filetype]['path']        self.filedict[filetype]['tkPath'].set(str(filepath))                print 'path: ', self.filedict[filetype]['path']         print 'tkpath: ', self.filedict[filetype]['tkPath']        self.refreshEntry(filetype)    def refreshEntry(self,filetype): #get user inputs        print 'refreshing'        filepath=self.filedict[filetype]['path']        print filetype, 'path: ', filepath        if os.path.isfile(filepath): #choose existing file            print 'file exsits'            try:                self.filedict[filetype]['tkPath'].set(str(filepath))            except:                message.showerror("Open Source File", "Failed to read file\n'%s" % filepath)        elif filetype== 'wordcloud' or filetype== 'tagFile': # new file             try:                 self.filedict[filetype]['tkPath'].set(str(filepath))            except:                 message.showerror("Failed to create file\n'%s'" % filepath)        elif filetype== 'addWord' or filetype== 'delWord': # take key board entry            try:                 self.filedict[filetype]['tkcontent'].get()            except:                 message.showerror("Failed to load \n'%s'" % filetype)            print "key board entry"            print self.filedict[filetype]['tkcontent'].get()        else:            print "File dose not exist"        print filetype, 'tkpath: ', self.filedict[filetype]['tkPath'].get()    def center(self):        ws = self.root.winfo_screenwidth()        hs = self.root.winfo_screenheight()        x = int( (ws/2) - (self.w/2) )        y = int( (hs/2) - (self.h/2) )        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))            def closeWindow(self,filetype,window): #triger refresh and check checkbutton status        self.refreshEntry(filetype)        if len(self.filedict[filetype]['path'])==0:            if filetype=='tagFile':                self.keywords.set(0)            if filetype=='useDictPath':                self.userDict.set(0)        if filetype=='addWord':            print len(self.filedict[filetype]['tkcontent'].get()), self.filedict[filetype]['tkcontent'].get()            if len(self.filedict[filetype]['tkcontent'].get())==0:                self.addDict.set(0)        if filetype=='delWord':            if len(self.filedict[filetype]['tkcontent'].get())==0:                self.delDict.set(0)        window.destroy()            def newEntryWindow(self,filetype, switch): # extra window type one        if switch.get() == 1:            newwindow = tk.Toplevel()            newframe0 = Frame(newwindow)            newframe0.pack(expand=True, fill=BOTH, padx=5,pady=5,side=TOP,anchor='w')            if filetype=='tagFile':                labeltext = '新建关键词保存文件'            elif filetype == 'useDictPath':                labeltext = '设置自定义字典'            tk.Label(newframe0, text=labeltext, justify = LEFT).pack(padx=20,pady=0,side=LEFT,anchor='w')            tk.Button(newframe0, text='...', command=lambda: self.getFilePath(filetype), width=3,height=1).pack(padx=10, pady=0, side=RIGHT,anchor='e')            textEntry=tk.Entry(newframe0,textvariable=self.filedict[filetype]['tkPath'],validate='focusout', validatecommand=lambda: self.refreshEntry(filetype)).pack(padx=0, pady=0, side=RIGHT,anchor='e')                    newframe2 = Frame(newwindow)            newframe2.pack(expand=True, fill=BOTH, padx=5,pady=5,side=TOP,anchor='w')            tk.Button(newframe2, text='确定', command=lambda: self.closeWindow(filetype,newwindow), width=6,height=1).pack(padx=10, pady=0, side=TOP,anchor='n')            newwindow.mainloop()    def alterWords(self, filetype, switch): #extra window type two        if switch.get() == 1:            newwindow = tk.Toplevel()            newframe0 = Frame(newwindow)            newframe0.pack(expand=True, fill=BOTH, padx=5,pady=5,side=TOP,anchor='w')            if filetype=='addWord':                labeltext = '向字典添加新词'            elif filetype == 'delWord':                labeltext = '从字典删除词'            newframe = Frame(newwindow)            newframe.pack(expand=True, fill=BOTH, padx=5,pady=5,side=TOP,anchor='w')            tk.Label(newframe, text=filetype,justify = LEFT).pack(padx=20,pady=0,side=LEFT,anchor='w')            textEntry=tk.Entry(newframe,textvariable=self.filedict[filetype]['tkcontent']).pack(padx=10, pady=0, side=RIGHT,anchor='e')            newframe2 = Frame(newwindow)            newframe2.pack(expand=True, fill=BOTH, padx=5,pady=5,side=TOP,anchor='w')                        tk.Button(newframe2, text='确定', command=lambda: self.closeWindow(filetype,newwindow), width=6,height=1).pack(padx=10, pady=0, side=TOP,anchor='n')            newwindow.mainloop()                def getCanvasColor(self):        self.background_color.set(tkColorChooser.askcolor()[1])        self.canvasColorBnt.configure(bg = self.background_color.get())            def numberValidate(self, num):        if not isinstance( num.get(), ( int, long ) ):            num.set(int(num.get()))        def pathFrame(self):        LabelFrame = tk.LabelFrame(bd=1, labelanchor='nw', text = '设置路径', padx=0, pady=0)        LabelFrame.pack(padx=20,pady=5,side=TOP)               textframe = Frame(LabelFrame)        textframe.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        tk.Label(textframe, text='文本文件:',justify = LEFT).pack(padx=20,pady=0,side=LEFT,anchor='w')        tk.Button(textframe, text='...', command=lambda: self.getFilePath("text"), width=3,height=1).pack(padx=10, pady=0, side=RIGHT,anchor='e')        textEntry=tk.Entry(textframe,textvariable=self.filedict['text']['tkPath'],validate='focusout', validatecommand=lambda: self.refreshEntry("text"),width=15).pack(padx=0, pady=0, side=RIGHT,anchor='e')         stopwordframe = Frame(LabelFrame)        stopwordframe.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        tk.Label(stopwordframe, text='停止词文件:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Button(stopwordframe, text='...', command=lambda: self.getFilePath("stopword"), width=3, height=1).pack(padx=10, pady=0, side=RIGHT)        tk.Entry(stopwordframe,textvariable=self.filedict['stopword']['tkPath'],validate='focusout', validatecommand=lambda: self.refreshEntry("stopword"),width=15).pack(padx=0, pady=0, side=RIGHT)        maskframe = Frame(LabelFrame)        maskframe.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        tk.Label(maskframe, text='底图文件: ').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Button(maskframe, text='...', command=lambda: self.getFilePath("mask"), width=3, height=1).pack(padx=10, pady=0, side=RIGHT)        tk.Entry(maskframe,textvariable=self.filedict['mask']['tkPath'],validate='focusout', validatecommand=lambda: self.refreshEntry("mask"),width=15).pack(padx=0, pady=0, side=RIGHT)        wordcloudframe = Frame(LabelFrame)        wordcloudframe.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        tk.Label(wordcloudframe, text='词云保存路径:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Button(wordcloudframe, text='...', command=lambda: self.getFilePath("wordcloud"), width=3, height=1).pack(padx=10, pady=0, side=RIGHT)        tk.Entry(wordcloudframe,textvariable=self.filedict['wordcloud']['tkPath'],validate='focusout', validatecommand=lambda: self.refreshEntry("wordcloud"),width=15).pack(padx=0, pady=0, side=RIGHT)    def canvasFrame(self):        LabelFrame2 = tk.LabelFrame(bd=1, labelanchor='nw', text = '词云画布', padx=0, pady=0, width=500)        LabelFrame2.pack(padx=20,pady=5,side=TOP)                canvasframe1 = Frame(LabelFrame2)        canvasframe1.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe1, text='画布宽:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Spinbox(canvasframe1,from_=10,to=1680,increment=50,textvariable=self.canvas_w,width=15).pack(padx=20, pady=0, side=RIGHT,anchor='w')        canvasframe2 = Frame(LabelFrame2)        canvasframe2.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe2, text='画布高:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Spinbox(canvasframe2,from_=10,to=1050,increment=50,textvariable=self.canvas_h,width=15).pack(padx=20, pady=0, side=RIGHT,anchor='w')        canvasframe3 = Frame(LabelFrame2)        canvasframe3.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe3, text='画布边距:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Spinbox(canvasframe3,from_=0,to=50,increment=5,textvariable=self.margin,width=15).pack(padx=20, pady=0, side=RIGHT,anchor='w')        canvasframe4 = Frame(LabelFrame2)        canvasframe4.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe4, text='画布底色:').pack(padx=21, pady=0, side=LEFT,anchor='w')        self.canvasColorBnt = tk.Button(canvasframe4, text='选择颜色', command=lambda: self.getCanvasColor(), bg = self.background_color.get(), width=16, height=1)        self.canvasColorBnt.pack(padx=19, pady=0, side=RIGHT)        canvasframe9 = Frame(LabelFrame2)        canvasframe9.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe9, text='着色方法:').pack(padx=20, pady=0, side=LEFT,anchor='w')        Radiobutton(canvasframe9,text="背景图", variable=self.colorMode, value=2).pack(padx=15, pady=0, side=RIGHT, anchor='w')              Radiobutton(canvasframe9,text="随机", variable=self.colorMode, value=1).pack(padx=0, pady=0, side=RIGHT, anchor='w')        canvasframe5 = Frame(LabelFrame2)        canvasframe5.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe5, text='词云字体:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Entry(canvasframe5,textvariable=self.font,width=17).pack(padx=19, pady=0, side=RIGHT)        #ttk.Combobox(canvasframe5, textvariable=self.font, values=tkFont.families(),width=15).pack(padx=20, pady=0, side=RIGHT)        canvasframe6 = Frame(LabelFrame2)        canvasframe6.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe6, text='词云最大字体:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Entry(canvasframe6,textvariable=self.max_font_size,validate='focusout'                 , validatecommand=lambda: self.numberValidate(self.max_font_size),width=17).pack(padx=19, pady=0, side=RIGHT)        canvasframe7 = Frame(LabelFrame2)        canvasframe7.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe7, text='词云字数上限:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Entry(canvasframe7,textvariable=self.max_words,validate='focusout'                 , validatecommand=lambda: self.numberValidate(self.max_words),width=17).pack(padx=19, pady=0, side=RIGHT)        canvasframe8 = Frame(LabelFrame2)        canvasframe8.pack(expand=True, fill=BOTH, padx=5,pady=1,side=TOP,anchor='w')        Label(canvasframe8, text='随机度:').pack(padx=20, pady=0, side=LEFT,anchor='w')        tk.Entry(canvasframe8,textvariable=self.random_state,validate='focusout'                 , validatecommand=lambda: self.numberValidate(self.max_words),width=17).pack(padx=19, pady=0, side=RIGHT)            def optionFrame(self):        LabelFrame3 = tk.LabelFrame(bd=1, labelanchor='nw', text = '个性化', padx=0, pady=0, width=500)        LabelFrame3.pack(padx=20,pady=5,side=TOP)                chnframe = Frame(LabelFrame3)        chnframe.pack(expand=True, fill=BOTH, padx=5,pady=0,side=TOP,anchor='w')        Checkbutton(chnframe, text="中文文件", variable=self.Chinese).pack(padx=20, pady=0, side=LEFT, anchor='w')                modeframe = Frame(LabelFrame3)        modeframe.pack(expand=True, fill=BOTH, padx=5,pady=0,side=TOP,anchor='w')        Label(modeframe, text='分词模式:').pack(padx=20, pady=0, side=LEFT,anchor='w')        Radiobutton(modeframe,text="搜索", variable=self.cutMode, value=3).pack(padx=5, pady=0, side=RIGHT, anchor='w')             Radiobutton(modeframe,text="全分", variable=self.cutMode, value=2).pack(padx=5, pady=0, side=RIGHT, anchor='w')             Radiobutton(modeframe,text="默认", variable=self.cutMode, value=1).pack(padx=5, pady=0, side=RIGHT, anchor='w')                     optionframe = Frame(LabelFrame3)        optionframe.pack(expand=True, fill=BOTH, padx=5,pady=0,side=TOP,anchor='w')        Checkbutton(optionframe, text="提取关键词", command=lambda: self.newEntryWindow('tagFile',self.keywords), variable=self.keywords).pack(padx=20, pady=0, side=TOP, anchor='w')        Checkbutton(optionframe, text="添加自定义字典", command=lambda: self.newEntryWindow('useDictPath',self.userDict), variable=self.userDict).pack(padx=20, pady=0, side=TOP, anchor='w')        Checkbutton(optionframe, text="添加新词", command=lambda: self.alterWords('addWord',self.addDict), variable=self.addDict).pack(padx=20, pady=0, side=TOP, anchor='w')        Checkbutton(optionframe, text="删除已有词", command=lambda: self.alterWords('delWord',self.delDict), variable=self.delDict).pack(padx=20, pady=0, side=TOP, anchor='w')                                                def packBtn(self):        bntframe = Frame()        bntframe.pack(expand=True, fill=BOTH, padx=30,pady=20,side=TOP,anchor='n')        tk.Button(bntframe, text='绘制词云', command=lambda: self.event(), width=10, height=2).pack(side=LEFT,anchor='sw')        tk.Button(bntframe, text='关闭窗口', command=lambda: self.close(), width=10, height=2).pack(side=RIGHT,anchor='se')    def close(self):        print "im trying to close"        self.status = 0        self.root.quit()        self.root.destroy()            def event(self):        print "**********************event() start actions**********************"                for filetype in ['text', 'stopword', 'mask', 'wordcloud', 'tagFile', 'useDictPath', 'addWord', 'delWord']:            self.refreshEntry(filetype)                     self.myWordCloudArgu = {   "textpath":self.filedict['text']['path']                                      , 'stopwordpath':self.filedict['stopword']['path']                                      , 'maskpath':self.filedict['mask']['path']                                      , 'savepath':self.filedict['wordcloud']['path']                                      , 'Chinese':self.Chinese.get()                                      , 'keywords': self.keywords.get()                                      , 'tagFile':  self.filedict['tagFile']['path']                                      , 'userDict':self.userDict.get()                                      , 'userDictPath':self.filedict['useDictPath']['path']                                      , 'addDict':self.addDict.get()                                      , 'addWord':self.filedict['addWord']['tkcontent'].get()                                      , 'delDict':self.delDict.get()                                      , 'delWord':self.filedict['delWord']['tkcontent'].get()                                      , 'cutMode':self.cutMode.get()                                      , 'colorMode': self.colorMode.get()                                      , 'canvas_w':self.canvas_w.get()                                      , 'canvas_h' : self.canvas_h.get()                                      , 'margin':self.margin.get()                                      , 'background_color':self.background_color.get()                                      , 'font':self.font.get()                                      , 'max_font_size':self.max_font_size.get()                                      , 'max_words':self.max_words.get()                                      , 'random_state':self.random_state.get()                                      }        if self.myWordCloudArgu['Chinese']:             if self.myWordCloudArgu['keywords']:                self.getKeyWords() # create a new file path            if self.myWordCloudArgu['userDict']:                self.getUserDict() # path of an existing file            if self.myWordCloudArgu['addDict']:                self.add2Dict() #may need to create new entry            if self.myWordCloudArgu['delDict']:                self.delfromDict()        self.createWordCloud()    def loop(self):        if self.status:            self.root.resizable(False, False)   #禁止修改窗口大小            self.pathFrame()            self.canvasFrame()            self.optionFrame()            self.packBtn()            self.center()                       #窗口居中            self.event()            self.root.mainloop()                ########################################################################try:        if __name__ == '__main__':        w = Window(1)        w.loop()except:    print "Unexpected error: ", sys.exc_info()    raw_input()

去掉小黑框vbs~

CreateObject("WScript.Shell").Run "cmd /c WordCloudCreator.exe",0

让用户更便利的setup.py

import osimport pythoncomfrom inspect import getsourcefilefrom win32com.shell import shell   from win32com.shell import shellcondef createQuickLnk(filepath,iconpath,folder,lnkname):    shortcut = pythoncom.CoCreateInstance(           shell.CLSID_ShellLink, None,           pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)    #set shortcut path    shortcut.SetPath(filepath)       if os.path.splitext(lnkname)[-1] != '.lnk':           lnkname += ".lnk"    lnkname = os.path.join(folder,lnkname)    print lnkname    #set icon path    if iconpath:        shortcut.SetIconLocation(iconpath, 0)    #set working dir    workDir = os.path.join(folder,"dist")    shortcut.SetWorkingDirectory(workDir)                shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)  if __name__ == '__main__':    basePath = os.path.abspath(getsourcefile(lambda:0))    print basePath        topDir = os.path.split(os.path.split(basePath)[0])[0]    target = os.path.join(topDir, "dist\WordCloudCreator.vbs")    if not os.path.exists(target):        topDir = os.path.split(basePath)[0]        target = os.path.join(topDir, "dist\WordCloudCreator.vbs")                    icon= os.path.join(topDir, "dist\Cloud.ico")    print topDir    print target    print icon    createQuickLnk(target,icon,topDir,"WordCloudCreator")

最后是一句再也不会忘记的咒语:

cxfreeze xxx.py --target-dir dirname --icon iconname


原创粉丝点击