2017-02-17 54 views
0

比方說,我有一個文本文件,其中包含以下內容(假設標題爲:名稱,鉛筆數量)Python - 如果文件中的兩行符合條件,則將這些行中的數字相加

Harry,3, 
Alexander,4, 
Rebecca,39, 
Rachel,7, 
Alexander,9, 
Harvey,5, 
Rebecca,11, 

這裏最主要的是Alexander和Rebecca都有多個條目。目前,我的代碼讀取文件中的行,只輸出行,忽略任何多個條目;即條目都是彼此分開的(我不確定我需要將代碼放在這裏 - 這只是美學的一般格式)。相反,我希望它將兩個數量一起添加到具有多個事件的任何名稱,然後將其輸出給用戶。

因此,舉例來說,輸出應該是這樣的:

Harry  3 
Alexander 13 
Rebecca  50 
Rachel  7 
Harvey  5 

我覺得我失去了一些東西明顯(道歉,如果我),但我怎麼會檢查是否有線路名稱匹配,然後如果他們這樣做,爲最終輸出添加數字?創建一個新文件來存儲這些新值會更容易嗎? 目前,我的線沿線的思考:

namesInFile = [] 
with open("Pencils.txt","r") as file: 
    for line in file: 
     pencilArr = line.split(",") 
     namesInFile.append(pencilArr[0]) 

     if namesInFile.count(pencilArr[0]) > 0: 
     do something 

但我不確定究竟如何去從在一個循環中創建不同的陣列添加數字?也許如果我初始化一個變量來跟蹤數量,但是那麼是否有可能只爲那些我知道具有匹配條件的變量進行這樣的操作。

謝謝!

回答

0

您可能需要使用一個Python字典這不是一個列表。您將要在dictionaries讀了,但是這是怎麼了可以用一個來實現:

name_pencil_dict = {} # Create the dictionary 
with open("Pencils.txt","r") as file: 
for line in file: 
    pencilArr = line.split(",") 
    name = pencilArr[0] 
    num_pencils = pencilArr[1] 

    if name not in list(name_pencil_dict.keys): 
     # Name not found, create new dictionary entry, initialize num pencils to zero 
     name_pencil_dict[name] = 0 

    # Add the number of pencils to the name's dictionary value 
    name_pencil_dict[name] += num_pencils 
1

不要使用列表,請使用字典。將人員姓名存儲爲密鑰並將其累計爲一個值。

names_in_file = {} 
with open("Pencils.txt","r") as file: 
    for line in file: 
     pencil_list = line.split(",") 
     names_in_file[pencil_list[0]] = names_in_file.get(pencil_list[0], 0) + int(pencil_list[1]) 

然後,在完成讀取文件後,通過在形成的字典中處理鍵和值來形成輸出文件。

out_content = '' 
for name, age in names_in_file.iteritems(): 
    out_content = '{}{}\t{}\n'.format(out_content, name, age) 
with out_file as open('path_to_out_file', "wt"): 
    out_file.write(out_content) 

注意:我重命名爲更Python名稱變量。

祝你好運:)!

+0

謝謝! 我可以問一下,out_content的存在目的是在「 out_content ='{} {} \ t {} \ n'.format(out_content,name,age)」行嗎? – Dovahkiin

2

一個defaultdict會是一個很不錯的:

import collections as co 

dd = co.defaultdict(int) 
with open("Pencils.txt","r") as fin: 
    for line in fin: 
     name,amount,blank = line.split(',') 
     dd[name] += int(amount) 

結果:

>>> dd 
defaultdict(<type 'int'>, {'Harvey': 5, 'Alexander': 13, 'Rebecca': 50, 'Rachel': 7, 'Harry': 3}) 
1

您也可以嘗試

file_obj = open('data.txt', 'r') 
dic = {} 
for line in file_obj: 
    arr = line.split(',')[:2] 
    if arr[0] in dic: 
     dic[arr[0]] += int(arr[1]) 
    else: 
     dic[arr[0]] = int(arr[1]) 


file_obj.close() 
相關問題