Skip to main content
 首页 » 编程设计

python之从统计文件中构建计数字典

2025年05月04日13Leo_wl

我有一个这样的统计文件:

字典计数.txt

apple   15 
orange  12 
mango   10 
apple   1 
banana  14 
mango   4 

我需要计算每个元素的数量并创建一个这样的字典:{'orange': 12, 'mango': 14, 'apple': 16, 'banana': 14}。我执行以下操作以实现此目的:

from __future__ import with_statement 
 
with open('dict-count.txt') as f: 
    lines = f.readlines() 
 
output = {} 
 
for line in lines: 
    key, val = line.split('\t') 
    output[key] = output.get(key, 0) + int(val) 
 
print output 

我特别关心这部分:

key, val = line.split('\t') 
output[key] = output.get(key, 0) + int(val) 

有更好的方法吗?或者这是唯一的方法?

谢谢。

请您参考如下方法:

对于小文件,您可以使用.readlines(),但这会一次性将文件的全部内容写入内存。您可以使用文件对象 f 作为迭代器来编写它;当你迭代它时,你一次得到一行输入。

因此,最简单的编写方法是使用 defaultdict,正如@Amber 已经展示的那样,但我的版本没有构建输入行列表;它只是构建字典。

我使用了简洁的变量名,比如 d 代替了 output 的字典。

from __future__ import with_statement 
from collections import defaultdict 
from operator import itemgetter 
 
d = defaultdict(int) 
 
with open('dict-count.txt') as f: 
    for line in f: 
        k, v = line.split() 
        d[k] += int(v) 
 
lst = d.items() 
 
# sort twice: once for alphabetical order, then for frequency (descending). 
# Because the Python sort is "stable", we will end up with descending 
# frequency, but alphabetical order for any frequency values that are equal. 
lst.sort(key=itemgetter(0)) 
lst.sort(key=itemgetter(1), reverse=True) 
 
for key, value in lst: 
    print("%10s| %d" % (key, value))