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章 安妮·琼斯 256 卡罗尔·李 第845章 史蒂夫·罗伯特·安德森 132 吉尔·汤普森
从程序的主函数中,我们需要给用户以下选项:根据身份证号查找姓名、根据姓名查找身份证号、退出程序。
选项1:用户选择根据身份证号码查找姓名: 使用 try/ except 并要求用户输入一个整数。 如果他们不输入整数,则打印错误消息。 如果他们确实输入了整数,则调用名为lookup_employee 的函数,该函数将 id 作为参数。 如果找到具有给定 ID 号的员工,则返回姓名。 否则,返回字符串“未找到员工” 回到main,打印返回结果。
选项 2:用户选择根据名称查找 ID: 要求用户输入名字和姓氏(不要要求中间名)。 调用名为lookup_id 的函数,该函数将名字和姓氏作为两个单独的字符串。 如果找到具有给定名字和姓氏的员工,请返回 ID 号。 否则,返回字符串“ID not found” 回到main,打印返回结果。
选项 3:退出循环并退出程序。
我运行了代码几次,但出现了错误。
提前谢谢您。
这些是代码中的问题
<space>
代替 <comma>
id_num
,同时输入cast to integar
keys, values
字典的 employees
。这是运行代码:
employees = {}
employees_names = {}
def load_employees():
with open("employees.txt") as file:
for line in file:
words = line.strip().split()
id_num, full_name = int(words[0]), words[1:]
first_name, *_, last_name = full_name
employees[id_num] = [(first_name, last_name)]
employees_names[(first_name, last_name)] = id_num
def lookup_id(first_name, last_name):
return employees_names.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()