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

从文本文件读取字典时遭遇IndexError: list index out of range错误的技术求助

解决'list index out of range'错误并实现员工信息展示与查询

你的问题根源在于手动解析字典字符串的方式不够健壮——当字典里的某个值(比如Skills对应的列表)包含你用来分割键值对的逗号时,split(', ')会把列表内部的逗号也当成键值对的分隔符,导致某些项无法用: 分割成键值对,自然就出现了IndexError。

最优解决方案:用ast.literal_eval解析合法Python数据结构

文本文件里的内容本身就是合法的Python字典格式(多个字典用空格分隔),完全不需要手动去拆分解析,直接用Python标准库的ast.literal_eval来安全解析即可,它能正确识别列表、字符串等嵌套结构。

修改后的代码如下:

import ast

def load_employees():
    employees = []
    with open("sample.txt", 'rt') as f:
        # 读取全部内容,处理换行并统一为空格分隔
        content = f.read().replace('\n', ' ')
        # 按'}{'分割多个字典的边界
        dict_strings = content.split('}{')
        # 修复每个字典的首尾符号,确保格式合法
        for i in range(len(dict_strings)):
            if i == 0:
                dict_strings[i] = dict_strings[i] + '}'
            elif i == len(dict_strings)-1:
                dict_strings[i] = '{' + dict_strings[i]
            else:
                dict_strings[i] = '{' + dict_strings[i] + '}'
        # 解析每个字典字符串并加入列表
        for ds in dict_strings:
            if ds.strip():
                employee = ast.literal_eval(ds)
                employees.append(employee)
    return employees

def view_employees():
    employees = load_employees()
    for emp in employees:
        # 按你期望的格式输出员工信息
        print(f"Email: {emp['Email']}")
        print(f"First Name: {emp['First Name']}")
        print(f"Last Name: {emp['Last Name']}")
        print(f"Department: {emp['Department']}")
        print(f"Position: {emp['Position']}")
        print(f"Salary: {emp['Salary']:.2f}")
        # 将Skills列表转为逗号分隔的字符串
        print(f"Skills: {', '.join(emp['Skills'])}")
        print()  # 空行分隔不同员工

def search_employee_by_email(email):
    employees = load_employees()
    # 不区分大小写匹配邮箱
    for emp in employees:
        if emp['Email'].lower() == email.lower():
            return emp
    return None

# 调用展示函数
view_employees()

# 示例:查询单个员工(取消注释即可使用)
# target_emp = search_employee_by_email("jbond@gmail.com")
# if target_emp:
#     print("查询到的员工信息:")
#     print(f"Email: {target_emp['Email']}")
#     print(f"Position: {target_emp['Position']}")
# else:
#     print("未找到该员工")

代码说明:

  1. load_employees函数:负责读取文本文件,处理多个字典的分割边界,安全解析每个字典并返回员工列表,是后续功能的基础。
  2. view_employees函数:调用加载函数获取数据,按照你想要的格式输出,其中薪资格式化为两位小数,技能列表转为易读的逗号分隔字符串。
  3. search_employee_by_email函数:实现你后续需要的单个员工查询功能,支持不区分大小写的邮箱匹配。

为什么不用eval?

eval虽然也能解析字典字符串,但ast.literal_eval更安全——它只解析合法的Python字面量(字典、列表、字符串、数字等),不会执行任意代码,避免了潜在的安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:37:45