You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python脚本仅提取{textblock_content}标签间首行文本的问题?

问题与解决方案

问题描述

需要提取TXT文件中{textblock_content}与{/textblock_content}之间的文本,但运行提供的Python脚本后,仅能提取introtext.txt中第一行的目标内容,无法获取其他行的符合条件的文本。

原脚本代码:

f = open("introtext.txt")
r = open("textcontent.txt", "w")
for l in f.readlines():
    if "{textblock_content}" in l:
        pos_text_begin = l.find("{textblock_content}") + 19
        pos_text_end = l.find("{/textblock_content}")
        text = l[pos_text_begin:pos_text_end]
        r.write(text)

f.close()
r.close()

问题原因

  1. 单行限制:原脚本只处理同时包含起始和结束标记的单行内容,如果目标文本跨多行(起始标记在某一行,结束标记在另一行),脚本会直接忽略这部分内容。
  2. 单一匹配:即使同一行存在多组标记,原脚本也只会提取第一组的内容,其余会被遗漏。
  3. 硬编码长度:用+19来跳过起始标记,一旦标记字符串长度变化(比如拼写修改),就会导致截取错误,应该用动态长度计算替代。

解决方案

场景1:所有标记与目标文本都在同一行(支持多组匹配)

这个脚本会遍历每一行,提取该行内所有符合条件的文本片段:

# 使用with上下文管理器自动管理文件关闭
with open("introtext.txt", "r") as input_file, open("textcontent.txt", "w") as output_file:
    start_tag = "{textblock_content}"
    end_tag = "{/textblock_content}"
    tag_start_len = len(start_tag)
    
    for line in input_file:
        current_position = 0
        # 循环查找当前行内的所有标记组
        while True:
            # 查找下一个起始标记的位置
            start_index = line.find(start_tag, current_position)
            if start_index == -1:
                break  # 没有更多起始标记,退出循环
            
            # 定位到起始标记后的内容起始点
            content_start = start_index + tag_start_len
            # 查找对应结束标记的位置
            end_index = line.find(end_tag, content_start)
            if end_index == -1:
                break  # 找不到对应的结束标记,跳过
            
            # 提取并写入目标文本,可根据需求添加换行符
            output_file.write(line[content_start:end_index] + "\n")
            # 更新当前位置,继续查找下一组标记
            current_position = end_index + len(end_tag)

场景2:目标文本跨多行(起始/结束标记不在同一行)

如果目标文本可能跨多行,需要切换到状态记录模式:遇到起始标记后开始记录内容,直到遇到结束标记为止:

with open("introtext.txt", "r") as input_file, open("textcontent.txt", "w") as output_file:
    start_tag = "{textblock_content}"
    end_tag = "{/textblock_content}"
    is_recording = False  # 标记是否处于记录状态
    content_buffer = []
    
    for line in input_file:
        # 检查是否进入记录状态
        if start_tag in line:
            is_recording = True
            # 提取当前行起始标记后的部分内容
            start_index = line.find(start_tag) + len(start_tag)
            content_buffer.append(line[start_index:])
        
        # 检查是否退出记录状态
        elif end_tag in line and is_recording:
            is_recording = False
            # 提取当前行结束标记前的部分内容
            end_index = line.find(end_tag)
            content_buffer.append(line[:end_index])
            # 将缓冲区的内容写入文件
            output_file.write("".join(content_buffer))
            content_buffer = []  # 清空缓冲区
        
        # 处于记录状态时,直接添加整行内容
        elif is_recording:
            content_buffer.append(line)
    
    # 可选:处理文件结束但未找到结束标记的情况
    if is_recording:
        print("警告:文件末尾存在未闭合的{textblock_content}标记")

额外说明

  • 使用with语句管理文件可以避免手动关闭文件时可能出现的资源泄漏问题,是Python操作文件的最佳实践。
  • 两种脚本都替换了原脚本中硬编码的+19,改用len(start_tag)动态计算标记长度,提升了代码的可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:20:38