统计个数

来源:互联网 发布:淘宝怎么查看收获地址 编辑:程序博客网 时间:2024/05/03 22:01

in 文件每行有三列,tab分隔,统计最后一列每个字符出现的字数,其实是数字,但是当作字符处理。没什么问题,主要是最后想要对dict 按key值排序出了问题,python3 的dict不能用sort 什么的,最后也只能搞成按字符排序,而不是按key的数值排序。

摘抄一段python 文档

>>> # regular unsorted dictionary>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}>>> # dictionary sorted by key>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])>>> # dictionary sorted by value>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])>>> # dictionary sorted by length of the key string>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
使用collections 里的 OrderedDict() ,写的时候试了下,把key值转换成int 来compare,ok,好丑

import collectionsfile=open('filename.txt','r')count={}f1=open('c3.txt','w')for lines in file.readlines():lines=lines.rstrip('\n')line=lines.split('\t')[2]if line in count:count[line]+=1else:count[line]=1f=open('out.txt','w')count=collections.OrderedDict(sorted(count.items(), key=lambda t: int(t[0])))for i in count:i=str(i)count[i]=str(count[i])f.write(i+'\t'+count[i]+'\n')f.close


0 0
原创粉丝点击