2017-02-17 51 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() 
相关问题