Python员工ID/姓名双向查询代码运行报错,请求排查修复
员工信息双向查询代码修复
原代码核心问题
- 文件分隔符错误:
employees.txt中ID与姓名用空格分隔,但代码里用split(",")拆分,会导致解包id_num, full_name时抛出ValueError(每行只能拆出1个元素,无法分配给两个变量)。 - 映射关系缺失:原代码仅存储了
(名, 姓) → ID的单向映射,按ID查询姓名需要的ID → 姓名反向映射完全缺失,导致lookup_employee永远返回"Employee not found"。 - 类型不匹配:原代码将ID以字符串存入字典,但查询时传入的是整数类型,类型不匹配无法命中键。
修复后的完整代码
# 维护两个字典分别存储双向映射 id_to_name = {} name_to_id = {} def load_employees(): with open("employees.txt") as file: for line in file: # 按空格分割,第一个元素为ID,剩余元素拼接为全名 parts = line.strip().split() id_num = parts[0] full_name = " ".join(parts[1:]) # 提取名和姓(兼容含中间名的情况) name_parts = full_name.split() first_name = name_parts[0] last_name = name_parts[-1] # 双向存储映射,ID转为整数保证查询匹配 id_to_name[int(id_num)] = full_name name_to_id[(first_name.lower(), last_name.lower())] = id_num def lookup_id(first_name, last_name): # 转为小写避免大小写敏感问题 return name_to_id.get((first_name.lower(), last_name.lower()), "ID not found") def lookup_employee(id_num): return id_to_name.get(id_num, "Employee not found") def main(): try: load_employees() except FileNotFoundError: print("Error: employees.txt 文件未找到,请确保文件在当前目录下。") return 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: ").strip() last_name = input("Enter the last name: ").strip() if not first_name or not last_name: print("Invalid input. Please enter both first and last name.") continue result = lookup_id(first_name, last_name) print(result) elif choice == "3": print("Exiting program...") break else: print("Invalid choice. Please choose 1, 2, or 3.") if __name__ == "__main__": main()
额外优化说明
- 新增
FileNotFoundError捕获,处理文件不存在的异常场景。 - 姓名查询转为小写,消除大小写输入差异导致的查询失败。
- 增加姓名输入非空校验,避免空输入引发的错误。
- 兼容员工全名含多个中间名的情况,正确提取名和姓。
内容的提问来源于stack exchange,提问作者user12860710
相关产品推荐
相关产品推荐

