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

字典的操作

为字典增加一项

dict[key] = value

  1. students = {"Z004":"John","T002":"Peter"}
  2. students
  3. Out[23]: {'T002': 'Peter', 'Z004': 'John'}
  4. students["S007"] = "Susan"
  5. students
  6. 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 方法,完全拷贝了父对象及其子对象。

字典浅拷贝实例:

  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 模块:

  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

示例:词频统计

第一步:输入文章

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

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

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

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

第六步:输出结果

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

                                         

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

普通版本

  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. hamletTxt=getText()
  8. words=hamletTxt.split()
  9. counts={}
  10. sumcount = 0
  11. for word in words:
  12. counts[word]=counts.get(word,0)+1
  13. sumcount = sumcount + 1
  14. items=list(counts.items())
  15. items.sort(key=lambda x:x[1],reverse=True)
  16. for i in range(10):
  17. word,count=items[i]
  18. print('{0:<10}{1:>5}'.format(word,count))
  19. #将统计结果写入文本文件中
  20. outfile = open('词频统计结果.txt', "w")
  21. lines = []
  22. lines.append('单词种类:'+str(len(items))+'\n')
  23. lines.append('单词总数:'+str(sumcount)+'\n')
  24. lines.append('词频排序如下:\n')
  25. lines.append('word\tcounts\n')
  26. s= ''
  27. for i in range(len(items)):
  28. s = '\t'.join([str(items[i][0]), str(items[i][1])])
  29. s += '\n'
  30. lines.append(s)
  31. print('\n统计完成!\n')
  32. outfile.writelines(lines)
  33. outfile.close()

排除特定词库

  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. hamletTxt=getText()
  12. words=hamletTxt.split()
  13. counts={}
  14. sumcount = 0
  15. for word in words:
  16. counts[word]=counts.get(word,0)+1
  17. sumcount = sumcount + 1
  18. counts_ex = counts.copy()
  19. for key in counts.keys():
  20. if key in excludes:
  21. counts_ex.pop(key)
  22. items=list(counts_ex.items())
  23. items.sort(key=lambda x:x[1],reverse=True)
  24. for i in range(10):
  25. word,count=items[i]
  26. print('{0:<10}{1:>5}'.format(word,count))
  27. #将统计结果写入文本文件中
  28. outfile = open('词频统计结果.txt', "w")
  29. lines = []
  30. lines.append('单词种类:'+str(len(items))+'\n')
  31. lines.append('单词总数:'+str(sumcount)+'\n')
  32. lines.append('词频排序如下:\n')
  33. lines.append('word\tcounts\n')
  34. s= ''
  35. for i in range(len(items)):
  36. s = '\t'.join([str(items[i][0]), str(items[i][1])])
  37. s += '\n'
  38. lines.append(s)
  39. print('\n统计完成!\n')
  40. outfile.writelines(lines)
  41. outfile.close()

GUI版本

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

Python字典使用--词频统计的GUI实现的更多相关文章

  1. 用Python实现一个词频统计(词云+图)

    第一步:首先需要安装工具python 第二步:在电脑cmd后台下载安装如下工具: (有一些是安装好python电脑自带有哦) 有一些会出现一种情况就是安装不了词云展示库 有下面解决方法,需看请复制链接 ...

  2. Python3.7 练习题(二) 使用Python进行文本词频统计

    # 使用Python进行词频统计 mytext = """Background Industrial Light & Magic (ILM) was starte ...

  3. 利用python实现简单词频统计、构建词云

    1.利用jieba分词,排除停用词stopword之后,对文章中的词进行词频统计,并用matplotlib进行直方图展示 # coding: utf-8 import codecs import ma ...

  4. (改进)Python语言实现词频统计

    需求: 1.设计一个词频统计的程序. 2.英语文章中包含的英语标点符号不计入统计. 3.将统计结果按照单词的出现频率由大到小进行排序. 设计: 1.基本功能和用法会在程序中进行提示. 2.原理是利用分 ...

  5. python实现简易词频统计-源码

    需求:给瓦尔登湖文章统计单词出现的频率 思路:首先读取文件并以空格分割得到列表,然后利用for循环遍历列表中的元素并把去掉列表元素中的符号,第三步去掉相同的元素,将列表转换为一个字典,最后按照键值对升 ...

  6. python:Hamlet英文词频统计

    #CalHamletV1.py def getText(): #定义函数读取文件 txt = open("hamlet.txt","r").read() txt ...

  7. 用Python来进行词频统计

    # 把语料中的单词全部抽取出来, 转成小写, 并且去除单词中间的特殊符号 def words(text): return re.findall('[a-z]+', text.lower()) def ...

  8. Python 词频统计

    利用Python做一个词频统计 GitHub地址:FightingBob [Give me a star , thanks.] 词频统计 对纯英语的文本文件[Eg: 瓦尔登湖(英文版).txt]的英文 ...

  9. spark ---词频统计(二)

    利用python来操作spark的词频统计,现将过程分享如下: 1.新建项目:(这里是在已有的项目中创建的,可单独创建wordcount项目) ①新建txt文件: wordcount.txt (文件内 ...

随机推荐

  1. Scala2.10.4在CentOS7中的安装与配置

    随着基于内存的大数据计算框架——spark的火爆流行,用于编写spark内核的Scala语言也随之流行开来.由于其编写代码的简洁性,受到了越来越多程序员的喜爱.我今天给大家展示的时Scala2.10. ...

  2. 【leetcode 简单】 第七十五题 第一个错误的版本

    你是产品经理,目前正在带领一个团队开发新的产品.不幸的是,你的产品的最新版本没有通过质量检测.由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的. 假设你有 n 个版本 [1, ...

  3. Linux下ssh的使用

    更多内容推荐微信公众号,欢迎关注: 摘抄自:https://www.cnblogs.com/kevingrace/p/6110842.html 对于linux运维工作者而言,使用ssh远程远程服务器是 ...

  4. windows程序设计.窗口.

    第一个windows窗口 #include <windows.h> /* Displays "Hello, World!" in client area */ LRES ...

  5. UNIX网络编程 第4章 基本TCP套接字编程

    本章的几个函数在很大程度上展示了面向对象与面向过程的不同之处.

  6. App劫持病毒剖析:你的应用是如何被替换的(病毒防范方法)

    App劫持病毒剖析:你的应用是如何被替换的(病毒防范方法) 一.App劫持病毒介绍 App劫持是指执行流程被重定向,又可分为Activity劫持.安装劫持.流量劫持.函数执行劫持等.本文将对近期利用A ...

  7. 将网址url中的参数转化为JSON格式

    网上方法很多,各种奇技淫巧,这里贴上一种较为正常的思路. 主要利用split对获取的字符串不断进行分割,最后获得所需要的格式. 代码如下 <!DOCTYPE html> <html ...

  8. aarch64_m3

    mrpt-stereo-camera-calibration-1.4.0-1.fc26.aarch64.rpm 2017-03-17 10:02 143K fedora Mirroring Proje ...

  9. 查看sql语句加锁信息

    问题: 最近使用quartz集群,总是报deadlock问题,所以需要查看一下执行的sql导致的加锁冲突. 步骤: 1.在要测试的库中创建指定表innodb_lock_monitor create t ...

  10. ASP .NET Core 2.0 MVC 发布到 IIS 上以后 无法下载apk等格式的文件

    ASP .NET Core MVC 发布到  IIS 上以后 无法下载apk等格式的文件 使用.NET Core MVC创建了一个站点,其他文件可以下载,但是后来又需求,就把手机端的apk合适的文件上 ...