2015-05-19 22 views
2

我需要一个程序来读取.txt文件中的信息,该文件包含一个人的姓名和他/她的年龄。诀窍是,可以有任何数量的名字和年龄,但他们也可以重复,但算作一个人。当有最小值和最大值时,用函数in.txt文件写出结果?

程序需要写上最年轻的,那么最老的人一个新的.txt文件内。

需要从看起来像这样读取的.TXT:程序与名称进行

再经过
Sarah 18 
Joshua 17 
Michael 38 
Tom 18 
Sarah 18 
Michael 38 

应该写入一个新的.txt文件是这样的:

Joshua 17 
Michael 38 

到目前为止,我有这样的:

def parse_info(): 
    info = open("info.txt", "r") 
    max_age = 0 
    max_name = '' 
    min_age = float('inf') 
    min_name = '' 

    for line in info: 
     m_list = line.split(" ") 
     if int(m_list[1]) > max_age: 
      max_age = int(m_list[1]) 
      max_name = m_list[0] 
     elif int(m_list[1]) < min_age: 
      min_age = int(m_list[1]) 
      min_name = m_list[0] 

    info.close() 

我不知道如何使程序中创建一个新的.txt和令状e最年轻和最古老。任何帮助?

回答

1

您可以使用文件对象的write() method写入字符串到文件

with open("new.txt", "w") as output_file: 

    output_file.write("{0} {1}\n".format(max_name, max_age)) 
    output_file.write("{0} {1}".format(min_name, min_age)) 
+0

但每当我尝试这一点,OUTPUT_FILE提示 “无效语法” – Hyun

+0

@Hyun很抱歉,我们是一个错字。错过了')'在这两个陈述中。更正了答案。现在希望它的工作 – nu11p01n73R

+0

啊,我怎么看不到?傻我。它似乎被破坏,但现在我有一个错误弹出为我自己的程序说,'max_name没有定义'。有关如何修复它的任何建议? – Hyun

1
def parse_info(): 
info = open("info.txt", "r") 
max_age = 0 
max_name = '' 
min_age = float('inf') 
min_name = '' 

for line in info: 
    m_list = line.split(" ") 
    if int(m_list[1]) > max_age: 
     max_age = int(m_list[1]) 
     max_name = m_list[0] 
    elif int(m_list[1]) < min_age: 
     min_age = int(m_list[1]) 
     min_name = m_list[0] 
info.close() 
return ((min_name,min_age),(max_name,max_age)) 
#end of function 
nameAge=parse_info() 
f = open("output.txt","w") 
f.write(nameAge[0][0]+" "+str(nameAge[0][1])+"\n") 
f.write(nameAge[1][0]+" "+str(nameAge[1][1])) 

应该工作

+0

没有错误或任何东西,但当它创建一个新文件时,它不会写入任何内容。 – Hyun

+0

不,它写入它,我已经测试,确保你有info.txt文件在同一个目录 – bubakazouba

0

你可以很轻松地让Python的做所有的辛勤工作相结合的特性具有如何对元组列表进行排序的属性的集合。

def parse_info(): 
    persons = set() 
    for line in open('info.txt'): 
     name, age = line.split() 
     persons.add((int(age), name)) # Note that age comes first 

    # At this point, we have removed all duplicates, now we need 
    # to extract the minimum and maximum ages; we can simply do 
    # this by converting the set to a list and then sort the list. 
    # If a list entry is a tuple, the default behaviour is that it 
    # sorts by the first entry in the tuple. 
    persons = sorted(list(persons)) 

    # Now write the data to a new file 
    fd = open('new_info.txt', 'w') 
    age, name = persons[0] 
    fd.write('Youngest: %s %d\n' % (name, age)) 
    age, name = persons[-1] 
    fd.write('Oldest: %s %d\n' % (name, age)) 

parse_info()