使用正则、循环、enumerate解析复杂字符串列表生成Pandas DataFrame的实现咨询
长列表结构化解析实现流程
核心识别规则
原始列表为线性排布的业务文本,可通过正则匹配定位三类固定格式的结构节点,其余无匹配的字符串均为对应节点的关联正文:
- 最高层级根节点:独立成元素的BAT编码字符串,作为每个表格行的唯一分类依据
- 法规关联节点:根节点后续独立出现的法规编号字符串,归属当前最近的根节点
- MOC关联节点:独立成元素的MOC标识字符串(指向特定BAT编码的合规证明方法),归属当前最近的目标根节点
实现步骤
- 预先定义三类节点的正则匹配模式,通过锚定字符串首尾边界避免普通文本误判
- 使用
enumerate遍历列表,动态维护当前正在归集的文本块状态(当前BAT编码、关联法规、已收集的正文内容) - 遍历到新的根节点时,将上一个文本块的归集结果存入临时集合,重置状态开启新块
- 遍历结束后补全最后一个未存入的文本块,将临时集合转换为结构化DataFrame
完整可运行代码
import re import pandas as pd # 原始示例数据 data = ['BAT.A.100', 'Regulation 2020-1233', 'this is the core text of', 'the regulation referenced ', 'MOC to BAT.A.100', 'this', 'is', 'one method of demonstrating compliance to BAT.A.100', 'BAT.A.120', 'Regulation 2020-1599', 'core text of the regulation ...', ' more free text','more free text', 'BAT.A.145', 'Regulation 2019-3333', 'core text of' ,'the regulation1111', 'MOC to BAT.A.145', 'here is how you can show compliance to BAT.A.145','more free text', 'MOC2 to BAT.A.145', ' here is yet another way of achieving compliance'] # 定义正则匹配规则(锚定首尾边界,避免正文内容误匹配) pat_bat = re.compile(r'^BAT\.[A-Z]+\.[0-9]+$') pat_reg = re.compile(r'^Regulation \d{4}-\d+$') pat_moc = re.compile(r'^MOC\d* to (BAT\.[A-Z]+\.[0-9]+)$') # 初始化归集变量 result_rows = [] current_bat = None current_reg = None current_text_pool = [] # 枚举遍历列表元素 for idx, content in enumerate(data): clean_content = content.strip() # 识别到新的BAT根节点,完成上一个块的归集 if pat_bat.match(clean_content): if current_bat is not None: result_rows.append({ "BAT_Code": current_bat, "Regulation_Ref": current_reg, "All_Related_Text": " ".join(current_text_pool).strip() }) # 重置状态开启新块 current_bat = clean_content current_reg = None current_text_pool = [] # 识别到法规节点,记录对应关联信息 elif pat_reg.match(clean_content): current_reg = clean_content # 识别到MOC节点,将节点标识本身加入内容池 elif pat_moc.match(clean_content): current_text_pool.append(clean_content) # 普通正文,加入当前块的内容池 else: current_text_pool.append(clean_content) # 遍历结束,存入最后一个未归集的块 if current_bat is not None: result_rows.append({ "BAT_Code": current_bat, "Regulation_Ref": current_reg, "All_Related_Text": " ".join(current_text_pool).strip() }) # 生成最终DataFrame final_df = pd.DataFrame(result_rows)
输出效果
生成的DataFrame共3行,分别对应三个唯一BAT编码,每行归集了对应编码下的法规引用、全部关联正文(含法规核心文本、所有MOC方法说明文本),可根据业务需求调整列名或内容拼接分隔符。
内容的提问来源于stack exchange,提问作者Prolle
相关产品推荐
相关产品推荐

