Python 元组、集合和字典 实例
来源:互联网 发布:400软件 编辑:程序博客网 时间:2024/05/10 04:18
def main(): # Prompt the user to enter a file filename = raw_input("Enter a filename: ").strip() infile = open(filename, "r") # Open the file wordCounts = {} # Create an empty dictionary to count words for line in infile: processLine(line.lower(), wordCounts) pairs = list(wordCounts.items()) # Get pairs from the dictionary items = [[x, y] for (y, x) in pairs] # Reverse pairs in the list items.sort() # sort pairs in items for i in range(len(items) - 1, len(items) - 11, -1): print(items[i][1] + "\t" + str(items[i][0]))# Count each word in the linedef processLine(line, wordCounts): line = replacePunctuations(line) # Replace punctuation with space words = line.split() for word in words: if word in wordCounts: wordCounts[word] += 1 else: wordCounts[word] =1# Replace punctuation in the line with spacedef replacePunctuations(line): for ch in line: if ch in "~@#$%^&*()_-+=~<>?/,.;:!{}[]|'\"": line = line.replace(ch, " ") return linemain()
编写程序统计一个文本文件中单词的出现次数,并将出现次数最多的单词和它们的出现次数按降序显示。字典对象没有sort方法,那么如何对它进行排序呢?将字典的每一对放入一个列表中,然后对这个列表排序。如果使用sort方法对这个列表排序,程序将按每对的第一个元素进行排序,但是我们对出现次数(每对的第二个元素)进行排序。因此,需要利用倒置每一对来创建一个新的列表,然后利用sort方法。
—摘自《Python 程序语言设计》 李娜译
0 0
- Python 元组、集合和字典 实例
- python中的 元组 字典 和集合
- Python 学习笔记 -- 变量、元组、列表、字典和集合
- python中列表、元组、字典和集合
- Python容器:列表、元组、字典和集合
- python的列表,元组,集合,字典
- 元组 列表 集合 字典 python
- python的列表、元组、字典、集合
- Python 列表、元组、字典、集合
- 【python基础】之元组 集合 字典
- Python 列表、元组、字典、集合 区别
- Python 列表 元组 字典 集合
- python(三) 元组 字典 集合
- python 元组和字典
- 11 - 元组、集合和字典
- 元组、列表、字典和集合
- python系列笔记三:Python容器:集合、元组、字典
- Python黑帽编程2.3 字符串、列表、元组、字典和集合
- 自定义下拉刷新控件 - RefreshableView(支持所有控件的下拉刷新)
- html5解决大文件断点续传
- css3垂直居中的几种方法
- web学习
- CodeForces 282CXOR and OR
- Python 元组、集合和字典 实例
- 优雅编程之这样考虑字符性能,你就“正常”了(二十二)
- BindService
- AIDL随记(绑定本地和远程service)
- curl模拟post请求提交
- 螺旋数组的C语言实现
- 飞机游戏中子弹与飞机的移动与边界源码
- 在phpstorm中利用post方法提交form表单后,在响应页面获取不到数据的解决办法
- Struts2 数据校验