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

如何读取txt文件为可操作字符串并转换为指定格式的字典

实现方案

你可以直接用以下Python代码完成需求,分为「读取txt文件为字符串」和「解析字符串生成目标字典」两步:

# 1. 读取本地txt文件为字符串
# 注意替换下面的文件路径为你自己的txt文件实际存储路径
with open("./course_student.txt", "r", encoding="utf-8") as file:
    file_content = file.read()

# 2. 解析字符串生成目标字典
result_dict = {}
current_course = None
# 逐行遍历处理,自动跳过空行
for line in file_content.splitlines():
    cleaned_line = line.strip()
    if not cleaned_line:
        continue
    # 判断当前行是否为课程代码(以冒号结尾)
    if cleaned_line.endswith(":"):
        current_course = cleaned_line[:-1]
        result_dict[current_course] = []
    # 否则是对应课程的学生姓名,加入列表
    else:
        if current_course:
            result_dict[current_course].append(cleaned_line)

# 打印验证结果
print(result_dict)

运行以上代码后,result_dict就是你需要的格式的字典。如果运行出现编码报错,把encoding="utf-8"替换为encoding="gbk"重试即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:54:01