python - 向字典键添加多个值
问题描述
我有一个文件列表,其中每个文件有两列。第一列包含单词,第二列包含数字。
我想从文件中提取所有唯一词,并对其中的数字求和。这是我能做到的...
第二个任务是计算找到单词的文件数量。我在这部分遇到了麻烦......我正在为此使用字典。
这是我的代码:
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 中。
解决方案
一种方法是使用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
推荐阅读
- c++ - 减少模板参数的数量
- jquery - 一页上的多个阅读更多(省略号)显示全部而不是单独显示每个部分
- java - Spring:带有 Jpa 和 Kafka 的 ChainedKafkaTransactionManager 不是原子的?
- java - 如何使用 JPA 创建 ENUM 数组列?
- c++ - 我是否总是必须使用 unique_ptr 来表达所有权?
- shell - 如何使用 shell 命令或 wget 从网页下载 .tgz 文件?
- android - 将base64字符串转换为pdf
- bash - 在 Scons 中将“-W1,-rpath=\$ORIGIN”替换为“-W1,-rpath,\$ORIGIN”
- javascript - Angularjs - 模态对话框显示在默认页面中
- google-sheets - 在 if/query 数据上使用求和公式有问题吗?