gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:51 25 4
gpt4 key购买 nike

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

字典计数.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))

关于python - 从统计文件中构建计数字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com