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

如何通过Python脚本自动化GoLand中YAML多层键的批量搜索?

用Python脚本批量搜索YAML中的多层键并定位位置

完全可以实现这个自动化需求,核心思路是遍历目标目录下的所有YAML文件,解析文件时保留行号信息,逐层匹配你要找的多层键(比如a.b.c.d),最后输出每个键对应的文件路径和行号。

实现步骤

  1. 安装依赖库
    普通的yaml库没法保留行号,所以要用ruamel.yaml,它能在解析YAML时记录每个节点的原始行号:
pip install ruamel.yaml
  1. 编写批量搜索脚本
    下面的脚本支持从文本文件读取300多个目标键,遍历指定目录下的所有YAML文件,递归查找多层键并记录位置:
from ruamel.yaml import YAML
import os

def find_key_in_node(node, key_parts, current_path, line_numbers, result, target_key_str):
    """递归查找多层键,记录行号"""
    if not key_parts:
        # 所有层级匹配完成,记录结果
        result.append({
            'file_path': current_path,
            'key': target_key_str,
            'line_number': line_numbers[-1]
        })
        return

    current_key = key_parts[0]
    # 处理字典类型的节点
    if isinstance(node, dict):
        for k, v in node.items():
            if k == current_key:
                # 获取当前键的行号(ruamel行号从0开始,加1转自然行号)
                line = node.lc.data[k][0] + 1
                find_key_in_node(v, key_parts[1:], current_path, line_numbers + [line], result, target_key_str)
    # 处理数组类型的节点(如果键可能在数组元素里)
    elif isinstance(node, list):
        for idx, item in enumerate(node):
            find_key_in_node(item, key_parts, current_path, line_numbers, result, target_key_str)

def batch_search_yaml_keys(target_dir, key_list_file, output_file):
    yaml = YAML()
    yaml.preserve_quotes = True  # 保留原文件引号格式
    result = []

    # 读取目标键列表
    with open(key_list_file, 'r', encoding='utf-8') as f:
        target_keys = [line.strip() for line in f if line.strip()]

    # 遍历目录下的所有YAML文件
    for root, _, files in os.walk(target_dir):
        for file in files:
            if file.endswith(('.yaml', '.yml')):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        data = yaml.load(f)
                        if data is None:
                            continue
                        # 逐个处理每个目标键
                        for key_str in target_keys:
                            key_parts = key_str.split('.')
                            find_key_in_node(data, key_parts, file_path, [], result, key_str)
                except Exception as e:
                    print(f"处理文件 {file_path} 出错: {str(e)}")

    # 输出结果到文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("文件路径\t目标键\t行号\n")
        for item in result:
            f.write(f"{item['file_path']}\t{item['key']}\t{item['line_number']}\n")
    print(f"搜索完成,结果已保存到 {output_file}")

# 配置参数
if __name__ == '__main__':
    TARGET_DIR = '/path/to/your/yaml/directory'  # 替换成你的YAML文件根目录
    KEY_LIST_FILE = 'target_keys.txt'  # 每行一个目标键,比如a.b.c.d
    OUTPUT_FILE = 'search_results.txt'
    batch_search_yaml_keys(TARGET_DIR, KEY_LIST_FILE, OUTPUT_FILE)

使用说明

  • 把300多个目标键逐行写入target_keys.txt文件,格式示例:
    a.b.c.d
    x.y.z
    foo.bar.baz
    
  • 修改脚本中的TARGET_DIR为你的YAML文件所在的根目录
  • 运行脚本后,结果会保存到search_results.txt,包含每个键对应的文件路径、键名和行号

注意事项

  • 如果YAML文件中有锚点(&)、合并(<<)等特殊语法,脚本依然能正常解析
  • 行号是目标键第一次出现的行号,若同一个键在文件中多次出现,会全部记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:40:34