【问题标题】:Parse and Replace String in YAML在 YAML 中解析和替换字符串
【发布时间】:2020-05-16 01:29:24
【问题描述】:

我需要用 Python 中的另一个字符串替换 YAML 中出现的每个字符串。

name: responses
new:
    sources:
    - table: response
      source: xxx
      tier: raw
      view: vresponses
      columns:
      - a
      - b
      - c
      - d
      - eff_dt

    extracts:
    - sql: >-
        CREATE or REPLACE TEMPORARY VIEW sql1
        AS
        SELECT distinct
         some_cols,
         {{ place-holder }}
        FROM
        vresponse AS RES
        inner JOIN tab2 AS SUR
        ON RES.SrveyId = SUR.SrveyId

    - sql: >-
        CREATE or REPLACE TEMPORARY VIEW sql1
        AS
        SELECT distinct
         some_cols2,
         {{ place-holder }}
        FROM
        vresponse2 AS RES
        inner JOIN tab3 AS SUR
        ON RES.x = SUR.y

从上面的示例中,我想遍历所有出现的-sql key,并替换所有出现在-sql 键下的sql 语句中文本{{ place-holder }} 的所有出现,并将它们替换为新值。

我已经尝试过了,但导致以下错误:

>>> input_file = "my_file.yaml"
>>> data = yaml.load(open(input_file))
>>> i = 0
>>> for k, v in data['new']['extracts'][i]:
...     val = v.replace('{{ place-holder }}', 'new_str')
...     print(val)
...     i = i + 1
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

替换后,我想将内容转储回 yaml 格式。我是 Python 和 YAML 的新手。谁能帮忙。

谢谢

【问题讨论】:

    标签: python python-3.x yaml


    【解决方案1】:

    如果您想将内容转储回 yaml,更简单的方法可能是逐行读取文件,在遇到 {{ place-holder }} 时将其替换为新值。

    input_file = "my_file.yaml"
    output_file = "out.yaml"
    with open(input_file, "r") as f_in:
        with open(output_file, "w") as f_out:
            for line in f_in:
                line.replace("{{ place-holder }}", "new_str")
                output_file.write(line)
    

    如果您想确保您的"{{ place-holder }}" 字符串位于-sql key 块内,那么您可以尝试进行操作。你会得到一个错误,因为在迭代字典的 (key, value) 时,你需要使用 items() 函数:

    for k, v in data["new"]["extracts"][i].items():
    

    希望这能回答你的问题。

    注意:最好在 with 块中打开文件,以便在退出块或出现错误时自动关闭它们。

    【讨论】:

      【解决方案2】:

      添加之前的响应,如果您想传递提取,您应该使用单独的 for 对其进行迭代:

      for extract in data["new"]["extracts"]:
          for k,v in extract.items():
              val = v.replace('{{ place-holder }}', 'new_str')
              print(val)
      

      【讨论】:

      • 工作正常.. 但我需要替换字符串并取回整个更新的 yaml(以及未更改的其余内容)并将其格式化为 yaml
      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 2015-08-10
      • 2011-02-05
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      相关资源
      最近更新 更多