从TXT文件创建python字典-值聚合

时间:2018-08-03 09:36:18

标签: python dictionary sum key-value-store

我有一个TXT文件,格式为

22px 31
11px 326
18px 8
13px 41
22px 43
11px 291

其中第一列是字体大小(“ px”),第二列是字符计数。有什么办法可以汇总(总和)所有字体大小(键)上的字符数(值),然后使用python字典除以总字符数?假定的解决方案应采用以下形式:

11px    83% # =(326+291)/(31+326+8+41+43+291)
13px    6%
18px    1%
22px    10%

1 个答案:

答案 0 :(得分:0)

无需打扰熊猫。文本文件是可迭代的。只需打开它,在行(字符串)上操作并填写字典即可。

file = "font.txt"

with open(file, "r") as f:
    dic = dict()
    for line in f:
        x = line.strip("\n").split(" ")

        key = int(x[0].strip("px"))
        value = int(x[1])

        if key not in dic.keys():
            dic[key] = [value]
        else:
            dic[key].append(value)

输出:

{22: [31, 43], 11: [326, 291], 18: [8], 13: [41]}

那么这很简单:

total_number_of_character = sum([sum(x) for x in dic.values()])
percentage = percentage = {key:sum(value)/total_number_of_character*100 for (key, value) in dic.items()}

输出:

{22: 10.0,
 11: 83.37837837837839,
 18: 1.0810810810810811,
 13: 5.540540540540541}