批量修改json文件中的标签

发布于:2025-05-11 ⋅ 阅读:(22) ⋅ 点赞:(0)

一、代码

import os
import json
import argparse
from pathlib import Path

def modify_json_labels(input_dir, output_dir=None, label_value="book"):
    """
    批量修改JSON文件中shapes下的label标签内容
    
    参数:
    input_dir (str): 输入JSON文件所在目录
    output_dir (str): 输出目录,默认为None(覆盖原文件)
    label_value (str): 要设置的label值,默认为"book"
    """
    # 确保输入目录存在
    if not os.path.exists(input_dir):
        raise FileNotFoundError(f"输入目录不存在: {input_dir}")
    
    # 如果未指定输出目录,使用输入目录(覆盖原文件)
    if output_dir is None:
        output_dir = input_dir
    else:
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
    
    # 获取所有JSON文件
    json_files = [f for f in os.listdir(input_dir) if f.endswith('.json')]
    
    if not json_files:
        print("未找到JSON文件")
        return
    
    modified_count = 0
    
    # 处理每个JSON文件
    for json_file in json_files:
        file_path = os.path.join(input_dir, json_file)
        output_path = os.path.join(output_dir, json_file)
        
        try:
            # 读取JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 修改label标签
            modified = False
            if 'shapes' in data and isinstance(data['shapes'], list):
                for shape in data['shapes']:
                    if 'label' in shape:
                        shape['label'] = label_value
                        modified = True
            
            if modified:
                # 写入修改后的JSON
                with open(output_path, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                modified_count += 1
                print(f"已修改: {json_file}")
            else:
                print(f"未修改(未找到shapes/label): {json_file}")
                
        except Exception as e:
            print(f"处理文件 {json_file} 时出错: {str(e)}")
    
    print(f"处理完成。共修改 {modified_count} 个文件,总文件数: {len(json_files)}")

if __name__ == "__main__":
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description='批量修改JSON文件中shapes下的label标签内容')
    parser.add_argument('input_dir', help='输入JSON文件所在目录')
    parser.add_argument('-o', '--output_dir', help='输出目录,不指定则覆盖原文件')
    parser.add_argument('-l', '--label', default='book', help='要设置的label值,默认为book')
    
    # 解析命令行参数
    args = parser.parse_args()
    
    # 执行修改操作
    try:
        modify_json_labels(args.input_dir, args.output_dir, args.label)
    except Exception as e:
        print(f"程序执行出错: {str(e)}")    

二、使用说明

# 直接修改原文件

python json_label_modifier.py /path/to/json/files 

# 指定输出目录

python json_label_modifier.py /path/to/json/files -o /path/to/output

# 指定新的label值

python json_label_modifier.py /path/to/json/files -l new_label_value


网站公告

今日签到

点亮在社区的每一天
去签到