2017-08-21 74 views
0
1st Text file format . 
cake,60 
cake,30 
tart,50 
bread,89 

2nd Text file format . 
cake,10 
cake,10 
tart,10 
bread,10 

我試過的代碼。字典python

from collections import defaultdict 
answer = defaultdict(int) 
recordNum = int(input("Which txt files do you want to read from ")) 
count = 1 
counter = 0 
counst = 1 
countesr = 0 
while recordNum > counter: 
    with open('txt'+str(count)+'.txt', 'r') as f: 
     for line in f: 
      k, v = line.strip().split(',') 
      answer[k.strip()] += int(v.strip()) 
      count = count+1 
      counter = counter+1 
print(answer) 

問題所在。

I want the dictionary to be {'cake': '110', 'tart': '60', 'bread': '99'} 

but it prints like this {'cake': '30', 'tart': '50', 'bread': '89'} 

取而代之的是「蛋糕」的值從txt文件與其他蛋糕值加一和二它得到了最新的值替換。我將如何解決這個問題。另外我試圖做到這一點,如果我寫3,它會打開並添加3 txt文件,名爲,txt1.txt,txt2.txt和txt3.txt

+1

無法重現此。它適用於我。然而,它提供了110個蛋糕(30 + 60 + 10 + 10),並對文件名進行了硬編碼。 – MSeifert

+0

硬編碼文件名是什麼意思? –

+0

嗯,我不喜歡'input',所以我只創建了兩個文件,只是迭代它們而不是'while recordNum> counter:'。 – MSeifert

回答

2

問題是,你的第二個文件不讀取:

Which txt files do you want to read from 2 
defaultdict(<class 'int'>, {}) 
defaultdict(<class 'int'>, {'cake': 60}) 
defaultdict(<class 'int'>, {'cake': 90}) 
defaultdict(<class 'int'>, {'tart': 50, 'cake': 90}) 
defaultdict(<class 'int'>, {'tart': 50, 'bread': 89, 'cake': 90}) 
>> terminating 

你可以進行這些修改可以讀取所有文件(注:這是假定你的文本文件被命名爲txt1.txt,txt2.txt,txt3.txt等..):

from collections import defaultdict 
answer = defaultdict(int) 
number_of_records = int(input("How many text files do you want to read?")) 
for i in range(1, number_of_records+1): 
    with open('txt{}.txt'.format(i), 'r') as file: 
     for line in file: 
      k, v = line.strip().split(',') 
      answer[k] += int(v) 
print(answer) 


How many text files do you want to read? 
>> 2 
defaultdict(<class 'int'>, {'bread': 99, 'tart': 60, 'cake': 110}) 
>> terminating 
0

不知道代碼是pythonic的方式,但爲我工作和硬編碼。

x={} 
y={} 
with open("a.txt") as file: 
    for i in file: 
     (key, val) = i.split(',') 
     if key in x.keys(): x[key]=x[key]+int(val.rstrip()) 
     else: x[key] = int(val.rstrip()) 

with open("b.txt") as file: 
    for i in file: 
     (key, val) = i.split(',') 
     if key in y.keys(): y[key]=y[key]+int(val.rstrip()) 
     else: y[key] = int(val.rstrip()) 

print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) | set(y) } 

這可能會幫助您: Merge and sum of two dictionaries