You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件empList转换为字典并实现员工信息查询?

解决方案:将员工列表文本转换为字典并实现查询功能

需求说明:现有如下Python代码,需要将empList生成的文本文件内容转换为字典,实现输入员工编号后,输出对应员工的姓名、部门及费率,预期输出示例如下。

原代码

empList="""201911007,James,Butt,Accounting,365;
201203008,Josephine,Darakjy,Marketing,365;"""

def createFiles():
    f = open("empList.txt","w")
    f.write(empList)
    f.close
num=int(input('Enter Employee Number: '))
print('''Name:
Department:
Rate: 
''')

预期输出

Enter Employee Number: 201911007
Name: James Butt
Department: Accounting
Rate: 365

修改后的完整代码

empList="""201911007,James,Butt,Accounting,365;
201203008,Josephine,Darakjy,Marketing,365;"""

def createFiles():
    f = open("empList.txt","w")
    f.write(empList)
    f.close()  # 修复:添加括号执行关闭操作

# 构建员工信息字典
def build_emp_dict():
    emp_dict = {}
    with open("empList.txt", "r") as f:
        content = f.read()
        # 拆分记录并过滤空内容
        records = [rec.strip() for rec in content.split(";") if rec.strip()]
        for rec in records:
            emp_num, first_name, last_name, dept, rate = rec.split(",")
            # 员工编号作为键,存储拼接后的姓名、部门、费率
            emp_dict[int(emp_num)] = {
                "name": f"{first_name} {last_name}",
                "department": dept,
                "rate": rate
            }
    return emp_dict

# 执行流程
createFiles()
emp_dict = build_emp_dict()
num = int(input('Enter Employee Number: '))

# 查询并输出结果
if num in emp_dict:
    emp_info = emp_dict[num]
    print(f'''Name: {emp_info["name"]}
Department: {emp_info["department"]}
Rate: {emp_info["rate"]}''')
else:
    print("未找到对应员工编号")

关键说明

  1. 修复文件关闭问题:原代码中f.close未加括号,不会实际执行文件关闭操作,修改为f.close()确保资源释放
  2. 构建字典逻辑:读取文件内容后,按分号拆分每条员工记录,再按逗号拆分字段,将员工编号转为整数作为字典的键,对应值存储拼接后的姓名、部门、费率
  3. 查询与输出:根据输入的员工编号在字典中查询,存在则格式化输出对应信息,不存在则提示未找到

内容的提问来源于stack exchange,提问作者Griffeminie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:50:33