【发布时间】: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但没有使用它 -
这只是我的代码的一部分。请帮我弄清楚如何修复这部分代码。