如何批量提取文本中特定字符串间的内容并转换为dataframe列表
实现方案
现有代码的核心问题
str.index()仅返回第一次匹配的位置,无法遍历提取所有符合条件的文本块- 提取的原始块包含冗余短横线、多余空格,未做结构化清洗,无法直接转换为DataFrame
- 未使用上下文管理器打开文件,存在文件句柄泄露风险
完整可运行实现
以下代码采用逐行状态机的方式匹配目标块,对文本格式的容错性更高,可适配更大规模的文件读取:
import pandas as pd # 存储所有转换完成的DataFrame df_list = [] # 状态标记:是否正在收集一个目标数据块 in_block = False # 缓存当前块的所有文本行 current_block_lines = [] # 逐行读取文件,避免大文件一次性加载占用过高内存 with open('test.txt', 'r', encoding='utf-8') as f: for line in f: stripped_content = line.strip() # 匹配块起始条件:4个空格开头 + "Length" if stripped_content.startswith('Length') and line.startswith(' '): in_block = True current_block_lines = [line] continue if in_block: # 匹配块结束条件:行去掉首尾空白后全为短横线(兼容不同长度的分隔线) if set(stripped_content) == {'-'}: # 清洗当前块内容生成DataFrame # 处理表头 raw_header = current_block_lines[0] headers = [col.strip() for col in raw_header.replace('-', '').split() if col.strip()] # 处理数据行 data_rows = [] for row_line in current_block_lines[1:]: clean_line = row_line.strip() # 跳过块内的空行 if not clean_line: continue row_values = [int(val.strip()) for val in row_line.replace('-', '').split() if val.strip()] data_rows.append(row_values) # 存入最终列表 df_list.append(pd.DataFrame(data_rows, columns=headers)) # 重置状态 in_block = False current_block_lines = [] continue # 非结束标记行,加入当前块缓存 current_block_lines.append(line) # 验证输出结果 for i, df in enumerate(df_list): print(f"第{i+1}个数据块:") print(df)
效果说明
针对你提供的示例文件,运行后df_list会包含2个符合要求的DataFrame:
- 第一个块对应Code:44N下的3行尺寸数据
- 第二个块对应Code:40N下的4行尺寸数据
结构和你预期的输出完全一致。
注:代码中块结束的判断没有硬编码固定长度的短横线字符串,只要分隔行全为短横线即可识别,避免因文件内分隔线长度微调导致匹配失败。
内容的提问来源于stack exchange,提问作者user026
相关产品推荐
相关产品推荐

