如何将含多组Summary的无序TXT转换为指定格式的Python字典?
提取TXT文件中的列车运行时间与多组Summary字典
需求说明
从无序结构的TXT文件中完成两个任务:
- 提取列车运行的精确结束时间(对应文件中
train End字段的值) - 将文件中多组编号的
Summary模块(如Summary1、Summary2)分别转换为独立字典,每组内的键值对独立存储
TXT文件示例
Parameters selected: Fix Path Until: 6/9/2024 train End: 11/6/2024 Min. Float Days: 0 Options: True, False, Nav Summary1: Num of CLASS 1 NECESSARY found: 8 Num of Shorts found in the path: 1110 Num of Lengths found in the path: 1313 Summary2: Num of CLASS 1 NECESSARY found: 10 Num of Shorts found in the path: 1114 Num of Lengths found in the path:4567
尝试过的代码(未达到预期)
summary1 = dict() result = [] a= pd.read_table('F.txt',header=None, delimiter=None)[0].to_list() if 'summary1:' in a: for x in a: print(x)
期望输出
train_end_time: '11/6/2024' summary1: {'Num of CLASS 1 NECESSARY found': '8','Num of Shorts found in the path': '1110','Num of Lengths found in the path': '1313'} summary2: {'Num of CLASS 1 NECESSARY found': '10','Num of Shorts found in the path': '1114','Num of Lengths found in the path': '4567'}
解决方案代码
不需要用Pandas,直接逐行读取文件处理更简单:
def parse_train_file(file_path): train_end_time = None summaries = {} current_summary_key = None current_dict = None with open(file_path, 'r') as f: for line in f: line = line.strip() # 跳过空行 if not line: continue # 提取列车结束时间 if line.startswith('train End:'): _, time = line.split(':', 1) train_end_time = time.strip() continue # 识别Summary块的开始 if line.startswith('Summary') and line.endswith(':'): current_summary_key = line.lower().rstrip(':') current_dict = {} summaries[current_summary_key] = current_dict continue # 处理Summary内的键值对 if current_dict is not None and ':' in line: key, value = line.split(':', 1) current_dict[key.strip()] = value.strip() return train_end_time, summaries # 调用示例 train_time, summary_dicts = parse_train_file('F.txt') # 打印结果 print(f'train_end_time: {repr(train_time)}') for key, val in summary_dicts.items(): print(f'{key}: {val}')
代码说明
- 逐行读取文件,跳过空行,避免无效内容干扰
- 识别
train End:行,提取并存储列车结束时间 - 匹配
SummaryX:格式的行,作为新字典的标识,初始化空字典 - 在Summary块内,将每行按
:分割为键和值,去除多余空格后存入当前字典 - 最终返回提取到的列车时间和所有Summary字典的集合
内容的提问来源于stack exchange,提问作者eric
相关产品推荐
相关产品推荐

