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

如何批量修改图像标注txt文件首列数值(仅替换首列2为7)

仅替换标注文件第一列数值的解决方案

问题场景

我有多个存储图像目标标注框坐标的.txt文件,每个文件行数不固定,内容格式示例如下:

2 0.063542 0.192593 0.021528 0.185185
2 0.106944 0.298148 0.030556 0.300000
2 0.186806 0.600000 0.061111 0.577778

原本尝试通过字符串全局替换的方式,把第一列的2修改为7,代码如下:

for txtfile in txtfiles:
    with open(path + os.sep + txtfile, 'r') as file:
        filedata = file.read()
    # Replace the target string
    filedata2 = filedata.replace('2', '7')

但这种全局替换会把所有包含2的字符都替换(比如0.063542会被改成0.063547),需要实现仅替换每一行第一列的2。

可行解决方案

方法一:逐行拆分处理

逐行读取文件内容,拆分每行的字段后修改第一列,再重新拼接写入文件。这种方式逻辑直观,适配格式固定的标注文件:

import os

# 替换为你的标注文件所在目录
target_dir = "标注文件路径"
txt_files = [f for f in os.listdir(target_dir) if f.endswith('.txt')]

for filename in txt_files:
    file_path = os.path.join(target_dir, filename)
    
    # 读取并处理每一行
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    processed_content = []
    for line in lines:
        line = line.strip()
        if not line:
            processed_content.append(line)
            continue
        # 拆分字段,修改第一列
        parts = line.split()
        if parts[0] == '2':
            parts[0] = '7'
        processed_content.append(' '.join(parts))
    
    # 写入处理后的内容
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(processed_content))

方法二:正则表达式精准替换

使用正则匹配行首独立的2(确保是第一列的数值),替换为7。这种方式无需拆分字段,处理效率更高:

import os
import re

target_dir = "标注文件路径"
txt_files = [f for f in os.listdir(target_dir) if f.endswith('.txt')]

# 正则规则:匹配行首的2,后面必须跟空格或换行(确保是第一列的独立值)
replace_pattern = re.compile(r'^2(?=\s|$)', re.MULTILINE)

for filename in txt_files:
    file_path = os.path.join(target_dir, filename)
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 仅替换符合规则的2
    processed_content = replace_pattern.sub('7', content)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(processed_content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:12:15