2015-05-04 47 views
-1

我需要一个程序来读取.txt文件中的信息,该文件包含一个人的姓名和他/她的年龄。诀窍是,可以有姓名和年龄的任何金额,但他们也可以重复,但算一个人如何使用def从文件读取和打印信息?

所以.txt文件可以是随机的,但遵循名1 AGE-1的平台:

Sarah 18 
Joshua 17 
Michael 38 
Tom 18 
Sarah 18 
Michael 38 

Python已经被告知,打印出来的最年轻和最老的人变成了一个新的.txt文件

我猜在新文件的印刷应该是这样的:

Joshua 17 
Michael 38 

但我真的不知道如何甚至开始。

我希望我是对的,当我开始编码是这样的:

info = open("info.txt", "r") 

list = info.read() 
print (list) 

info.close() 

但我不知道如何确定最古老和最年轻的都以def。 任何提示或建议,可以让我在正确的轨道上?

+1

通过 “与DEF”,你的意思使用功能? –

+3

您需要逐行读取文件。你需要将每一行分成一个名称/年龄对。您需要跟踪迄今为止看到的最年轻的人,并且在您阅读每行时阅读最古老的人。最后,你需要输出最新的和最新的人到一个新的文件。你需要哪部分帮助? – chepner

回答

1

您正处于正确的轨道上。我建议下面的代码,但我会让在写入到文件部分,您:

def parse_info(): #If you need, the function can be wrapped up in a function like this. 
    #Notice that you can edit and pass info via arguments, like filename for example 
    info = open("info.txt", "r") 
    max_age = 0 
    max_name = '' 
    min_age = float('inf') #sentinel just for the comparison 
    min_name = '' 

    for line in info: 
     m_list = line.split(" ") #Represents 'Sarah 18' as ['Sarah', '18'] 
     if int(m_list[1]) > max_age: #Compares if you have found an age higher than any other already found 
      max_age = int(m_list[1]) 
      max_name = m_list[0] 
     elif int(m_list[1]) < min_age: #Compares if you have found an age lower than any other already found 
      min_age = int(m_list[1]) 
      min_name = m_list[0] 

    print ('Max age: ', max_name, ' ', max_age) 
    print ('Min age: ', min_name, ' ', min_age) 

    info.close() 
3

使用字典将是很好的位置:

my_dict = {} 
with open('your_file') as f: 
    for x in f: 
     name, age = x.strip().split() 
     my_dict[name] = age 
print max(my_dict.items(), key=lambda x:x[1]) 
print min(my_dict.items(), key=lambda x:x[1]) 
0
file = open("sort_text.txt") 
columnAge = [] 
for line in file: 
    columnAge.append(line.split(" ")[1].strip() + " " + line.split(" ")[0].strip()) 
columnAge.sort() 
print(columnAge[0].split(" ")[1] + " " + columnAge[0].split(" ")[0]) 
columnAge.sort(reverse=True) 
print(columnAge[0].split(" ")[1] + " " + columnAge[0].split(" ")[0]) 
file.close() 

输出:

Joshua 17 
Michael 38 

参考文献:

list_sort
string_split