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

如何从含标题与正文区块的文件生成有序字典?

问题解决:生成对应标题的有序字典

核心问题分析

你遇到的问题大概率是因为所有标题共用了同一个列表对象,或者在切换新标题时没有重新创建新的列表,导致后续内容都追加到同一个列表里,最终所有标题都指向同一组内容。

解决方案代码

from collections import OrderedDict

def parse_file_to_ordered_dict(file_path):
    ordered_dict = OrderedDict()
    current_key = None
    current_list = []
    
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            # 跳过分隔线和空行
            if not line or line.startswith('*' * 16):
                # 保存当前标题的内容并重置状态
                if current_key and current_list:
                    ordered_dict[current_key] = current_list.copy()
                    current_list.clear()
                    current_key = None
                continue
            
            # 识别标题行
            if line.startswith('* Header title'):
                # 先保存上一个标题的内容(如果存在)
                if current_key and current_list:
                    ordered_dict[current_key] = current_list.copy()
                    current_list.clear()
                # 提取标题文本
                current_key = line[2:].strip()
            # 识别内容行
            elif line.startswith('* +'):
                if current_key is not None:
                    # 去掉开头的"* ",保留内容
                    current_list.append(line[2:].strip())
    
    # 处理文件末尾的最后一组内容
    if current_key and current_list:
        ordered_dict[current_key] = current_list
    
    return ordered_dict

# 使用示例
d = parse_file_to_ordered_dict('your_file.txt')
for key, value in d.items():
    print(f"{key}: {value}")

关键步骤说明

  • 初始化current_key记录当前处理的标题,current_list存储当前标题对应的内容行
  • 逐行处理时:
    • 跳过分隔线和空行,遇到空行时会把当前标题的列表存入字典并重置状态
    • 遇到标题行时,先保存上一个标题的内容(如果有的话),再更新current_key为新标题,同时清空current_list
    • 遇到内容行时,将处理后的文本追加到current_list中
    • 文件遍历结束后,别忘了保存最后一组标题和内容

验证结果

针对你提供的示例文件,运行后会得到预期的有序字典:

OrderedDict([
    ('Header title 1', ['+ trig apple', '+ targ beans', '+ trig grapes', '+ targ berries']),
    ('Header title 2', ['+ trig beans', '+ targ joke', '+ trig help', '+ targ me'])
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:45:54