如何使用def从文件中读取和打印信息?

时间:2022-09-06 13:13:10

I need a program that would read information from a .txt file, which contains a person's name and his/her age. The trick is that there can be any amount of names and ages, but they also can repeat but count as one person.

我需要一个程序来读取.txt文件中的信息,该文件包含一个人的姓名和他/她的年龄。诀窍是,可以有任何数量的名称和年龄,但他们也可以重复,但算作一个人。

So the .txt file can be random but follow the platform of Name1 Age1:

所以.txt文件可以是随机的,但是遵循Name1 Age1的平台:

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

Python has to be told to print out the youngest and oldest person into a new .txt file?

必须告诉Python将最年轻和最老的人打印成新的.txt文件?

I'm guessing the printing in the new file should look like:

我猜测新文件中的打印应该如下所示:

Joshua 17
Michael 38

But I really do not know how to even start.

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

I hope I'm right when I start coding like this:

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

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

list = info.read()
print (list)

info.close()

But I don't know how to determine the oldest and youngest with def. Any tips or suggestions that could set me on the right track?

但我不知道如何用def来确定最年长和最年轻的人。任何可以让我走上正轨的提示或建议?

3 个解决方案

#1


Using Dictionary will be Good here:

在这里使用字典会很好:

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])

#2


You are on the right track. I suggest the following code, but I'll let the writing-to-file part to you:

你走在正确的轨道上。我建议使用以下代码,但我会将写入文件部分告诉您:

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


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()

Output:

Joshua 17
Michael 38

References:

list_sort
string_split

#1


Using Dictionary will be Good here:

在这里使用字典会很好:

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])

#2


You are on the right track. I suggest the following code, but I'll let the writing-to-file part to you:

你走在正确的轨道上。我建议使用以下代码,但我会将写入文件部分告诉您:

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


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()

Output:

Joshua 17
Michael 38

References:

list_sort
string_split