【发布时间】:2020-09-25 13:08:35
【问题描述】:
我正在用 python 制作一个电话簿搜索程序,它在文本文件中搜索学校的姓名输入。在程序中,要求用户输入姓氏或名字和姓氏。然后程序将搜索文本文件并打印与输入的电话号码相匹配的姓名。
因此,如果用户输入 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
if line[1] == last_name in line: # This condition is to ensure a line is printed if only a last name is used
print(line[0].capitalize(), line[1].capitalize(), ",", line[2])
elif line[1] == last_name and line[0] == first_name in line: # when a first and last name is used
print(line[0].capitalize(), line[1].capitalize(), ",", line[2])
else:
continue
我知道我的问题在于条件句。如果我先使用 elif 条件,即使使用全名,它也会打印具有相同姓氏的名称。
我查看了有关 stackflow 的几个问题,看看我是否能弄清楚,但没有一个完全符合我的问题。另外,我想知道如何让逗号更接近姓氏,因为我的输出让它在姓氏前面浮动一个空格:John Adams,508-555-5555。
感谢您提供的所有帮助,并期待您传授的知识!
【问题讨论】:
-
您是否尝试过一次读取列表,然后将其转换为可以在内存中使用的 python 对象(如字典或其他东西)?
-
其中一些测试没有多大意义。例如,
line[1] == last_name in line。这等价于line[1] == last_name and last_name in line,而后者又等价于line[1] == last_name。它在line中的附加测试毫无意义,因为您已经知道它是否满足第一个条件。 -
@TomKarzes 啊,我不知道该声明中的逻辑。我会在以后的条件句中记住这一点。
标签: python list search conditional-statements