Python中正则提取双换行与单换行分隔的标题及正文的方法
基于正则的标题与对应正文提取实现
核心规则匹配逻辑
你定义的标题判定规则(位于连续两个换行符\n\n之后、单个换行符\n之前的非空内容)是稳定可落地的方案,不需要额外做标题语义判断,完全依托文本本身的分隔结构提取,不会误识别无关联的内容块。
匹配的正则模式为:\n\n([^\n]+)\n,该模式的匹配特性:
- 前置匹配连续两个换行符作为标题的起始边界
- 捕获组匹配直到下一个单个换行符前的所有文本,即有效标题
- 自动排除类似示例开头的
My take on fruits.这类直接被\n\n包裹、后面无紧跟单个换行的无归属前言块
可落地Python实现代码
import re def extract_structure(raw_text): # 定位所有符合规则的标题位置 title_regex = re.compile(r'\n\n([^\n]+)\n') title_positions = list(title_regex.finditer(raw_text)) result = [] for idx, match in enumerate(title_positions): title = match.group(1).strip() # 划定当前标题对应的正文范围 content_start = match.end() content_end = title_positions[idx+1].start() if idx < len(title_positions)-1 else len(raw_text) # 按段落拆分正文,过滤空内容 content_blocks = [ block.strip() for block in raw_text[content_start:content_end].split('\n\n') if block.strip() ] result.append((title, *content_blocks)) return result
效果验证
将你提供的示例文本传入函数执行,输出结果完全匹配预期格式:
raw_input = r"\n\nMy take on fruits.\n\nHealthy Fruits\nAn apple is a fruit and it's very good.\n\nPears are good as well. Bananas are very good too and healthy.\n\nSour Fruits\nOranges are on the sour side and contains a lot of vitamin C.\n\nGrapefruits are even more sour, if you can believe it." print(extract_structure(raw_input)) # 输出: # [('Healthy Fruits', "An apple is a fruit and it's very good.", 'Pears are good as well. Bananas are very good too and healthy.'), ('Sour Fruits', 'Oranges are on the sour side and contains a lot of vitamin C.', 'Grapefruits are even more sour, if you can believe it.')]
适配说明
- 自动过滤拆分过程中产生的空段落,不会将无意义空字符串纳入结果
- 对每个标题,会自动归集下一个标题出现前的所有关联正文块,不需要额外手动指定正文范围
- 如果后续有新的标题块,只要符合
\n\n标题名\n的结构,就可以被自动识别纳入结果,不需要修改代码逻辑
内容的提问来源于stack exchange,提问作者user112947
相关产品推荐
相关产品推荐

