2015-05-04 45 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