You need to enable JavaScript to run this app. Python如何修改现有代码实现TXT中Title到condition行的内容提取
优惠活动
大模型
产品
解决方案
定价
更多

Python如何修改现有代码实现TXT中Title到condition行的内容提取

原代码问题

现有实现仅在匹配到单行Title开头内容时直接写入输出文件,没有跨多行的状态跟踪逻辑,无法抓取Title起始行到condition终止行之间的连续文本。

实现思路

引入状态标记完成跨段抓取:

  • 用布尔变量标记当前是否处于「抓取段」内
  • 遇到以Title开头的行时,将标记置为抓取状态,同时初始化临时缓存存入该行内容
  • 抓取状态下逐行处理后续内容:
    • 遇到以condition开头的行时,将缓存中拼接完成的完整段落按要求格式写入输出文件,清空缓存、重置抓取标记
    • 普通文本行则去除首尾空白后追加到缓存,自动合并原文本中硬折行断开的句子
修改后代码
import re

is_collecting = False
content_buffer = ""

with open("doubt.txt", encoding="utf8") as src, open("myOutFile.txt", "w", encoding="utf8") as dst:
    for line in src:
        clean_line = line.rstrip()
        # 匹配到Title开头行,开启收集
        if re.search(r'^Title', clean_line):
            is_collecting = True
            content_buffer = clean_line
            continue
        # 收集状态下匹配到condition行,结束当前段落收集
        if is_collecting and re.search(r'^condition', clean_line):
            dst.write(f"**{content_buffer}**\n\n")
            is_collecting = False
            content_buffer = ""
            continue
        # 收集状态下的普通行,拼接进缓存
        if is_collecting:
            content_buffer += " " + clean_line.strip()
输出效果

代码会自动将原文本中因排版折行拆成多行的Title段落拼接为连贯整句,去掉硬换行,严格从Title行开始截取、在condition行前终止内容,完全匹配预期的提取格式,不会混入其他无关文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 05:15:06