employees = {}
def load_employees():
with open("employees.txt") as file:
for line in file:
id_num, full_name = line.strip().split(",")
first_name, *_, last_name = full_name.split()
employees[(first_name, last_name)] = id_num
def lookup_id(first_name, last_name):
return employees.get((first_name, last_name), "ID not found")
def lookup_employee(id_num):
if id_num in employees:
return employees[id_num]
else:
return "Employee not found"
def main():
load_employees()
while True:
print("\nChoose an option:")
print("1. Lookup name by ID number")
print("2. Lookup ID number by name")
print("3. Quit")
choice = input("Enter your choice: ")
if choice == "1":
try:
id_num = int(input("Enter the ID number: "))
result = lookup_employee(id_num)
print(result)
except ValueError:
print("Invalid input. Please enter an integer ID number.")
elif choice == "2":
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
result = lookup_id(first_name, last_name)
print(result)
elif choice == "3":
break
else:
print("Invalid choice. Please choose 1, 2, or 3.")
if __name__ == "__main__":
main()
我正试图编写一段代码,让您从名为employees.txt的项目(保存在保存该Python文件的同一文件夹中)中查找人员的姓名和ID,其中包含以下数据:
123鲍勃·史密斯
345 Anne Jones
256 Carol Lee
845 Steve Robert Anderson
132吉尔·汤普森
从程序的主要功能来看,我们需要为用户提供以下选项:根据身份证号码查找姓名,根据姓名查找身份证号码,然后退出程序。
选项1:用户根据身份证号码选择查找姓名:
使用try/except并要求用户输入一个整数。
如果他们没有输入整数,则打印一条错误消息。
如果他们确实输入了一个整数,那么调用一个名为lookup_eemployee的函数,该函数将id作为参数。
如果找到具有给定身份证号码的员工,请返回姓名。
否则,返回字符串Employee not found
返回主界面,打印返回结果。
选项2:用户根据名称选择查找ID:
要求用户输入名字和姓氏(不要要求输入中间名)。
调用一个名为lookup_id的函数,该函数将名字和姓氏作为两个独立的字符串。
如果找到了具有给定名字和姓氏的员工,请返回身份证号码。
否则,返回字符串“找不到ID”
返回主界面,打印返回结果。
选项3:退出循环并退出程序。
我运行了好几次代码,但它给了我错误。
提前谢谢。