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

如何基于字符串标识读取文本文件中指定内容区间的数据?

基于文本标记提取指定内容的实现方案

核心思路

无需依赖行数,只需匹配起始标记noms sommets和结束标记0004 Nice,逐行读取文本,提取两个标记之间(含标记本身)的内容即可。

示例代码(Python)

def extract_target_content(file_path):
    target_lines = []
    start_flag = False
    end_marker = "0004 Nice"
    
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            if line == "noms sommets":
                start_flag = True
                target_lines.append(line)
                continue
            if start_flag:
                target_lines.append(line)
                if line == end_marker:
                    break  # 匹配到结束标记后停止读取
    return target_lines

# 使用示例
result = extract_target_content("your_data_file.txt")
for line in result:
    print(line)

代码说明

  • 用start_flag标记是否进入目标内容区间
  • 遇到起始标记noms sommets时,开启标记并记录该行
  • 开启标记后,逐行记录内容,直到匹配到0004 Nice时终止读取
  • 自动跳过空行,避免无效内容干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:05:42