我正在用 python 制作一个电话簿搜索程序,该程序在文本文件中搜索学校名称输入。在该程序中,系统会要求用户提供姓氏或名字和姓氏。然后,程序将搜索文本文件并打印与输入的电话号码相匹配的姓名。
因此,如果用户输入 Adams,结果将是:
John Adams,508-555-5555
Quicy Adams,508-555-5556
如果用户输入 John Adams,则只会打印他的名字。
John Adams,508-555-5555
我的问题是,我的 for 循环条件逐行读取列表。无论是否使用全名,它将打印与姓氏匹配的所有名称。
这是我的代码:
while True:
original_name = input("Enter a last name, or first and last name: ") # prompt user for name
if original_name == "": # create condition for infinite loop to end
break
l_name = original_name.lower() # lower case to assist in finding a match
s_name = l_name.split() # split to allow a full name to become two variables
if len(s_name) == 1: # Set condition for last name if it is by itself to be properly placed in variable
last_name = s_name[0]
elif len(s_name) == 2: # Set condition for first name and last name to go into proper variables
first_name = s_name[0]
last_name = s_name[1]
else:
print("Error: Input needs to be no more than 2 names!") # error for when more than 2 names are given
f = open("phones.txt", 'r') # open text file being used
numbers = f.readlines() # read text file line by line
for line in numbers:
line = line.lower() # lower case to assist in finding a match
line = line.strip() # strip to get rid of new lines
line = line.split() # split to allow for both first and last name to match
我知道我的问题在于条件。如果我先使用 elif 条件,即使使用全名,它也会打印具有相同姓氏的名称。
我查看了 stackflow 上的几个问题,看看我是否能弄清楚,但没有一个完全符合我的问题。另外,我想知道如何让逗号更接近姓氏,因为我的输出让它在姓氏前面浮动一个空格: John Adams , 508-555-5555。
我感谢您提供的所有帮助,并期待您传授的知识!
冉冉说
犯罪嫌疑人X
相关分类