Python字典使用--词频统计的GUI实现

字典是针对非序列集合而提供的一种数据类型,字典中的数据是无序排列的。

字典的操作

为字典增加一项

dict[key] = value

 

[python] view plain copy
 
  1. students = {"Z004":"John","T002":"Peter"}  
  2.   
  3. students  
  4. Out[23]: {'T002': 'Peter', 'Z004': 'John'}  
  5.   
  6. students["S007"] = "Susan"  
  7.   
  8. students  
  9. Out[25]: {'S007': 'Susan', 'T002': 'Peter', 'Z004': 'John'}  

 

访问字典中的值

 

dict[key] 返回key对应的值value

dict.get(key,default)--返回字典中key对应的值,若未找到key,则返回default值,default值可不写

删除字典中的一项

del dict[key]

字典的遍历

遍历字典的键key

for key in dict.keys():print(key)

遍历字典的值value

for value in dict.values():print(value)

遍历字典的项

for item in dict.items():print(item)

是否一个键在字典中

注:值不能判断

in 或者 not in 

删除字典项目

dict.clear()--删除字典中的所有项目

dict.pop(key)--删除并返回字典中key对应的值

直接赋值、浅拷贝、深拷贝

直接赋值:其实就是对象的引用(别名)。

浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。

深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。

 

字典浅拷贝实例:

[python] view plain copy
 
  1. >>>a = {1: [1,2,3]}  
  2. >>> b = a.copy()  
  3. >>> a, b  
  4. ({1: [1, 2, 3]}, {1: [1, 2, 3]})  
  5. >>> a[1].append(4)  
  6. >>> a, b  
  7. ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})  

深度拷贝需要引入 copy 模块:

 

 

[python] view plain copy
 
  1. >>>import copy  
  2. >>> c = copy.deepcopy(a)  
  3. >>> a, c  
  4. ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})  
  5. >>> a[1].append(5)  
  6. >>> a, c  
  7. ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})  

http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

 

示例:词频统计

第一步:输入文章

第二步:建立用于词频计算的空字典

第三步:对文本的每一行计算词频,如果文章长度一般,则不需用一次读一行,一次便可读完。

第四步:从字典中获取数据对到列表中

第五步:对列表中的数据对交换位置,并从大到小进行排序

第六步:输出结果

下图所示为程序输出结果及输出的统计结果

                                         

汉字的词频统计、排除特定词集合的程序后续更新...

普通版本

[python] view plain copy
 
  1. def getText():    
  2.     txt=open('hamlet.txt','r').read()    
  3.     txt=txt.lower()    
  4.     for ch in "~@#$%^&*()_-+=<>?/,.:;{}[]|\'""":    
  5.         txt=txt.replace(ch,' ')    
  6.     return txt    
  7.     
  8. hamletTxt=getText()    
  9. words=hamletTxt.split()    
  10. counts={}    
  11. sumcount = 0  
  12. for word in words:    
  13.     counts[word]=counts.get(word,0)+1  
  14.     sumcount = sumcount + 1  
  15. items=list(counts.items())    
  16. items.sort(key=lambda x:x[1],reverse=True)    
  17. for i in range(10):    
  18.     word,count=items[i]    
  19.     print('{0:<10}{1:>5}'.format(word,count))    
  20.     
  21.  #将统计结果写入文本文件中    
  22. outfile = open('词频统计结果.txt', "w")    
  23. lines = []      
  24. lines.append('单词种类:'+str(len(items))+'\n')    
  25. lines.append('单词总数:'+str(sumcount)+'\n')    
  26. lines.append('词频排序如下:\n')    
  27. lines.append('word\tcounts\n')    
  28.     
  29. s= ''    
  30. for i in range(len(items)):    
  31.     s = '\t'.join([str(items[i][0]), str(items[i][1])])    
  32.     s += '\n'      
  33.     lines.append(s)    
  34. print('\n统计完成!\n')    
  35. outfile.writelines(lines)    
  36. outfile.close()  

排除特定词库

[python] view plain copy
 
  1. #排除词库  
  2. excludes = ['the','and','to','of','i','a','in','it','that','is',  
  3.             'you','my','with','not','his','this','but','for',  
  4.             'me','s','he','be','as','so','him','your']  
  5. def getText():      
  6.     txt=open('hamlet.txt','r').read()      
  7.     txt=txt.lower()      
  8.     for ch in "~@#$%^&*()_-+=<>?/,.:;{}[]|\'""":      
  9.         txt=txt.replace(ch,' ')         
  10.     return txt      
  11.       
  12. hamletTxt=getText()      
  13. words=hamletTxt.split()      
  14. counts={}      
  15. sumcount = 0    
  16. for word in words:      
  17.     counts[word]=counts.get(word,0)+1    
  18.     sumcount = sumcount + 1   
  19.   
  20. counts_ex = counts.copy()      
  21. for key in counts.keys():  
  22.     if key in excludes:  
  23.         counts_ex.pop(key)  
  24. items=list(counts_ex.items())      
  25. items.sort(key=lambda x:x[1],reverse=True)      
  26. for i in range(10):      
  27.     word,count=items[i]      
  28.     print('{0:<10}{1:>5}'.format(word,count))      
  29.       
  30.  #将统计结果写入文本文件中      
  31. outfile = open('词频统计结果.txt', "w")      
  32. lines = []        
  33. lines.append('单词种类:'+str(len(items))+'\n')      
  34. lines.append('单词总数:'+str(sumcount)+'\n')      
  35. lines.append('词频排序如下:\n')      
  36. lines.append('word\tcounts\n')      
  37.       
  38. s= ''      
  39. for i in range(len(items)):      
  40.     s = '\t'.join([str(items[i][0]), str(items[i][1])])      
  41.     s += '\n'        
  42.     lines.append(s)      
  43. print('\n统计完成!\n')      
  44. outfile.writelines(lines)      
  45. outfile.close()  

GUI版本

[python] view plain copy
 
  1. import tkinter as tk  
  2. from tkinter import ttk  
  3. from tkinter import scrolledtext  
  4. from tkinter import filedialog  
  5. from tkinter import messagebox as mBox  
  6.   
  7. #获取原文内容  
  8. def getText(DIR):  
  9.     txt=open(DIR,'r').read()  
  10.     return txt  
  11.     txt.close()  
  12.   
  13. #打开文件  
  14. def __opendir():  
  15.     srcText.delete('1.0', tk.END) # 先删除所有  
  16.           
  17.     # 打开文件夹对话框  
  18.     fname = filedialog.askopenfilename(filetypes=( ("Text file", "*.txt*"),("HTML files", "*.html;*.htm")))  
  19.     entryvar.set(fname) # 设置变量entryvar,等同于设置部件Entry  
  20.           
  21.     if not fname:  
  22.         mBox.showwarning('警告', message='未选择文件夹!')  # 弹出消息提示框  
  23.   
  24.     #显示需要统计的文本  
  25.     Txt=getText(fname)  
  26.     srcText.insert(tk.END, Txt)  
  27.               
  28.     srcText.update()  
  29.       
  30. #手动输入文件名时回车键触发        
  31. def srcEnter(event=None):  
  32.       
  33.     fname=DirEntry.get()  
  34.     if not fname:  
  35.         mBox.showwarning('警告', message='请选择文件!')  # 弹出消息提示框  
  36.           
  37.     Txt=getText(fname)  
  38.     srcText.insert(tk.END, Txt)  
  39.               
  40.     srcText.update()  
  41.   
  42. #词频统计  
  43. def wordFrequence():  
  44.     fname=DirEntry.get()  
  45.     if not fname:  
  46.         mBox.showwarning('警告', message='请选择文件!')  # 弹出消息提示框  
  47.   
  48.     txt=getText(fname)  
  49.       
  50.     #对原文进行小写,标点符号转换处理  
  51.     txt=txt.lower()  
  52.     for ch in '!"#$%&*()+,.-;:<=>?@[]\^_{}|`':  
  53.         txt=txt.replace(ch,' ')  
  54.   
  55.     #词频统计  
  56.     words=txt.split()  
  57.     counts={} #用空字典存储统计结果  
  58.     for word in words:  
  59.         counts[word]=counts.get(word,0)+1  
  60.   
  61.     #词频排序  
  62.     items=list(counts.items())  
  63.     items.sort(key=lambda x:x[1],reverse=True)  
  64.   
  65.     #输出排序结果  
  66.     num=0  
  67.     for i in range(len(counts)):  
  68.         word,count=items[i]  
  69.         num=i*count+num  
  70.   
  71.   
  72.     dstText.insert(tk.END, '单词种类:')  
  73.     dstText.insert(tk.END, str(len(items)))  
  74.     dstText.insert(tk.END, '\n')  
  75.     dstText.insert(tk.END, '单词总数:')  
  76.     dstText.insert(tk.END, str(num))  
  77.     dstText.insert(tk.END, '\n')  
  78.     dstText.insert(tk.END, '词频排序如下:\n')  
  79.     dstText.insert(tk.END, '#word:\t\t#counts:\n')  
  80.   
  81.     for i in range(len(counts)):  
  82.         word,count=items[i]  
  83.         dstText.insert(tk.END, word)  
  84.         dstText.insert(tk.END, '\t\t')  
  85.         dstText.insert(tk.END, count)  
  86.         dstText.insert(tk.END, '\n')  
  87.   
  88. def savefile():  
  89.     # 打开文件夹对话框  
  90.     dirname = filedialog.askdirectory()   
  91.     outvar.set(dirname) # 设置变量entryvar,等同于设置部件Entry  
  92.           
  93.     if not dirname:  
  94.         mBox.showwarning('警告', message='请选择保存位置!')  # 弹出消息提示框  
  95.   
  96.     fname=dirname+'\词频统计结果.txt'  
  97.     outfile = open(fname, "w")  
  98.     outfile.writelines(dstText.get(1.0,tk.END))  
  99.     outfile.close()  
  100.     mBox.showinfo('词频统计', '统计结果保存成功!')  
  101.   
  102. def dstEnter(event=None):  
  103.     dirname=outvar.get()  
  104.     if not dirname:  
  105.         mBox.showwarning('警告', message='请选择保存位置!')  # 弹出消息提示框  
  106.     fname=dirname+'\词频统计结果.txt'  
  107.     outfile = open(fname, "w")  
  108.     outfile.writelines(dstText.get(1.0,tk.END))  
  109.     outfile.close()  
  110.     mBox.showinfo('词频统计', '统计结果保存成功!')  
  111.       
  112. # Create instance  
  113. win = tk.Tk()     
  114.   
  115. # Add a title         
  116. win.title("词频统计GUI")  
  117.   
  118. # Disable resizing the GUI  
  119. win.resizable(0,0)  
  120.   
  121.   
  122. #---------------窗口控件介绍------------------#  
  123.   
  124. #打开文件对话框  
  125. SelDirButton = ttk.Button(win, command=__opendir, text='选择文件目录:')  
  126. SelDirButton.grid(row=0, column=0,sticky=tk.W,pady=3,padx=3)  
  127.   
  128. #文件的目录显示      
  129. entryvar = tk.StringVar()   
  130. DirEntry=ttk.Entry(win, width=30,textvariable=entryvar)  
  131. DirEntry.grid(row=1, column=0,sticky=tk.W,pady=3,padx=3)  
  132. DirEntry.bind('<Return>', func=srcEnter)  
  133.   
  134. #文件内容的显示  
  135. srcText = scrolledtext.ScrolledText(win,width=30,height=30)#内容输出框  
  136. srcText.grid(row=2, column=0,columnspan=1,sticky=tk.W,pady=3,padx=3)  
  137.   
  138. #词频统计按钮  
  139. CalcuButton = ttk.Button(win, command=wordFrequence, text='词频统计')  
  140. CalcuButton.grid(row=0, column=1,sticky=tk.W,pady=3,padx=3)  
  141.   
  142. #统计结果显示  
  143. dstText = scrolledtext.ScrolledText(win,width=30,height=30)#内容输出框  
  144. dstText.grid(row=2, column=1,columnspan=2,sticky=tk.W,pady=3,padx=3)  
  145.   
  146. #保存文件按钮  
  147. SavefileButton = ttk.Button(win, command=savefile, text='统计结果保存到:')  
  148. SavefileButton.grid(row=0, column=2,sticky=tk.W,pady=3,padx=3)  
  149.   
  150. #保存文件目录  
  151. outvar = tk.StringVar()   
  152. saveEntry=ttk.Entry(win, width=30,textvariable=outvar)  
  153. saveEntry.grid(row=1, column=1,columnspan=2,sticky=tk.W,pady=3,padx=3)  
  154. saveEntry.bind('<Return>', func=dstEnter)  
  155.   
  156.        
  157. #======================  
  158. # Start GUI  
  159. #======================  
  160. win.mainloop()  
[python] view plain copy
 
    1. <pre code_snippet_id="2297514" snippet_file_name="blog_20170328_1_7839256" name="code" class="python"><pre code_snippet_id="2297514" snippet_file_name="blog_20170328_1_7839256"></pre>  
    2. <pre></pre>  
    3. <pre></pre>  
    4. <pre></pre>  
    5. <pre></pre>  
    6. <pre></pre>  
    7. <pre></pre>  
    8. <pre></pre>  
    9. <pre></pre>  
    10. <pre></pre>  
    11. <pre></pre>  
    12. <pre></pre>  
    13. <pre></pre>  
    14. <pre></pre>  
    15. <pre></pre>  
    16. <pre></pre>  
    17. <pre></pre>  
    18. <pre></pre>  
    19. <pre></pre>  
    20. <pre></pre>  
    21. <pre></pre>  
    22. <pre></pre>  
    23. <pre></pre>  
    24. <pre></pre>  
    25. <pre></pre>  
    26. <pre></pre>  
    27. <pre></pre>  
    28. <pre></pre>  
    29. <pre></pre>  
    30. <pre></pre>  
    31. <pre></pre>  
    32.                     </pre>  
posted @ 2017-11-09 10:09  py小蟒蛇  阅读(683)  评论(0编辑  收藏  举报