【问题标题】:Loop for continuous input, output data from list in file, quit if input is equal to q or quit循环连续输入,从文件列表中输出数据,如果输入等于q则退出或退出
【发布时间】:2020-05-08 20:15:47
【问题描述】:

我有以下代码根据用户输入从给定的文本文件中提取数据:

def read_file():

    students = []
    f = open('file.txt', 'r')
    for line in f.readlines():
        data = {}
        lines = ' '.join(line.split()).split()
        data[''] = int(lines[5])
        data[''] = float(lines[3])
        data[''] = float(lines[2])
        data[''] = line[1:6].rstrip(' ')
        students.append(data)
def search_student(students):
    student_search = input('Search for a student: ').lower()
    while student_search != 'q' and student_search != 'quit':
        for student in students:
            if student_search in student['Student Info'].lower():
                print_student_info(student)
                break
        student_search = input('Search for a student: ').lower()

此程序返回以下输出:

>>> Search for a student: 
>>> allen
>>> word: Allen, Age: 12, Height: 5'4, GPA: 3.8
>>> Search for a student:
>>> quit
>>> 

输入将提示程序根据用户输入的单词从文本文件中提取特定数据。这一切都很好。如果在文件中找不到该单词,我无法弄清楚如何添加将提示输入另一个输入的功能。

现在,如果在文件中找不到该词,程序只会要求再次搜索。但是,在要求再次搜索之前,我需要它说“在文本文件中找不到单词”之类的内容。

这是我正在寻找的输出:

>>> Search for a student:
>>> Jim
>>> Word: Jim, Age: 20, Height: 6'1, GPA: 2.5
>>> Search for a student:
>>> Molly
>>> Your searched student could not be found.
>>> Search for a student:
>>> Eddy
>>> Word: Eddy, Age: 15, Height: 5'6, GPA: 4.0
>>> Search for a student:
>>> quit
>>> 

我觉得这样的事情应该可以工作:

def search_student(file):
student_search = input('Search for a student: ').lower()
while student_search != 'q' and student_search != 'quit':
    for student in students:
        if student_search in student['Student Info'].lower():
            print_student_info(student)
            student_search = input('Search for a student: ').lower()
        else:
            print("Your searched student could not be found.")
            student_search = input('Search for a student: ').lower()

但它只是输出无论我输入什么单词,都找不到您搜索的学生。即使输入一个在第一个代码中工作的学生,现在也不再工作了。即使键入 quit 也不再退出循环。请帮忙。

新输出:

>>> Search for a student: 
>>> Allen
>>> Your searched student could not be found.
>>> Search for a student:
>>> quit
>>> Your searched student could not be found. 
>>> Search for a student:

【问题讨论】:

  • 您可以添加您的输入吗?
  • 我添加了它。你能帮忙吗?
  • 我可以,但请给我你的file
  • @Rose16 您正在迭代 file 但没有使用它
  • 这只是我的代码的一部分。请帮我弄清楚如何修复这部分代码。

标签: python loops input


【解决方案1】:

代码中有一个错误。它说for f in file,但随后又使用file。我认为您需要将那部分更改为:

        for f in file:
            if user_search in f['Data Info'].lower():
                print(data_info)
                break

【讨论】:

  • 我对代码进行了这个更改,但我仍然没有工作。
【解决方案2】:

您的代码中的问题是您正在使用循环来搜索单词。如果文件中的第一个单词不等于您搜索的单词,它将进入 else 条件。你需要在 for 循环结束后移动这个 else 条件来执行。

def info_search(file):
    user_search = input('Search for a word: ').lower()
    while user_search != 'q' and user_search != 'quit':
        for f in file:
            if user_search in f['Data Info'].lower():
                print(data_info)
                user_search = input('Search for a word: ').lower()
        else:
            print("Your searched word could not be found.")
            user_search = input('Search for a word: ').lower()
    return

【讨论】:

  • komatiraju032 这仅适用于一个循环。在循环一次之后,它只会对每个输入说“找不到您搜索的单词”。
【解决方案3】:

我不知道你的数据是什么,Data Info 是什么,但如果你只有文件,你可以使用下面的代码。

def info_search(lines):
    user_search = ''
    while True:
        user_search = input('Search for a word: ').lower()
        if user_search in ("q", "quit"):
            break
        for line in lines:
            if user_search in line.lower():
                print("Your searched word[{0}] found.".format(user_search))
                break
        else:
            print("Your searched word[{0}] could not be found.".format(user_search))

with open(filename, 'r') as file:
    lines = file.readlines()

info_search(lines)

【讨论】:

    【解决方案4】:

    所以我花了一些时间来找出问题所在。 首先,我假设您的file.txt 具有以下格式:

    Allan 12 5'4 3.8    
    Eddy 15 5'6 4.0  
    

    字段是姓名、年龄、身高、GPA。所以这里是读取文本文件的函数(请注意更改):

    def read_file():
        students = []
        f = open('file.txt', 'r')
        for line in f.readlines():
            data = {}
            lines = ' '.join(line.split()).split()
            data['Name'] = str(lines[0])
            data['Age'] = int(lines[1])
            data['Height'] = str(lines[2])
            data['GPA'] = float(lines[3])
            data[''] = line[1:4].rstrip(' ')
            students.append(data)
        return students
    

    然后为了搜索学生信息,我使用了以下代码:

    def search_student(students):
        found = False
        student_search = input('Search for a student: ').lower()
        while student_search != 'q' and student_search != 'quit':
            for student in students:
                if student_search in student['Name'].lower():
                    print_student_info(student)
                    found = True
                    break
            if found==False:
                print('Your searched student could not be found.')
            student_search = input('Search for a student: ').lower()
    

    最后打印学生信息:

    def print_student_info(student):
        print('Word: {}, Age: {}, Height: {}, GPA: {}'.format(student['Name'],student['Age'],student['Height'],student['GPA']))    
    

    定义完这些函数后,现在我们可以运行这两行代码了:

    students = read_file()
    search_student(students)
    

    这是我得到的结果:

    Search for a student: molly
    Your searched student could not be found.
    Search for a student: david
    Your searched student could not be found.
    Search for a student: allan
    Word: Allan, Age: 12, Height: 5'4, GPA: 3.8
    Search for a student: q
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2021-08-24
      • 1970-01-01
      • 2019-03-19
      • 2014-12-12
      • 1970-01-01
      相关资源
      最近更新 更多