首页 > 解决方案 > 向字典键添加多个值

问题描述

我有一个文件列表,其中每个文件有两列。第一列包含单词,第二列包含数字。

我想从文件中提取所有唯一词,并对其中的数字求和。这是我能做到的...

第二个任务是计算找到单词的文件数量。我在这部分遇到了麻烦......我正在为此使用字典。

这是我的代码:

import os
from typing import TextIO

currentdir = " " #CHANGE INPUT PATH
resultdir = " " #CHANGE OUTPUT ACCORDINGLY

if not os.path.exists(resultdir):
    os.makedirs(resultdir)

systemcallcount ={}    
for root, dirs, files in os.walk(currentdir):
    for name in files:


        outfile2 = open(root+"/"+name,'r')
        for line in outfile2:
            words=line.split(" ")
            if words[0] not in systemcallcount:
                systemcallcount[words[0]]=int(words[1]) 
            else:
                systemcallcount[words[0]]+=int(words[1]) 



        outfile2.close()


for keys,values in systemcallcount.items():
    print(keys)
    print(values)  

例如我有两个文件 -

file1  file2
a  2    a 3
b  3    b 1 
c  1     




so the output would be -

a 5 2
b 4 2
c 1 1

解释输出的第二列 a 是 2,因为它出现在两个文件中,而 c 是 1,因为它只出现在 file1 中。

在此处输入图像描述

标签: pythonpython-3.x

解决方案


一种方法是使用collections.defaultdict. 您可以创建一个set单词,然后为每个文件、每个单词增加字典计数器。

from collections import defaultdict

d = defaultdict(int)

for root, dirs, files in os.walk(currentdir):
    for name in files:

        with open(root+'/'+name,'r') as outfile2:
            words = {line.split()[0] for line in outfile2}
            for word in words:
                d[words[0]] += 1

推荐阅读