[英]Parse and Replace String in YAML
我需要用 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 的新手。 任何人都可以请帮忙。
谢谢
如果您想将内容转储回 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
块中打开文件是一个很好的做法,以便在退出块或出现错误时自动关闭它们。
添加之前的响应,如果您想传递提取物,您应该使用单独的for
迭代它们:
for extract in data["new"]["extracts"]:
for k,v in extract.items():
val = v.replace('{{ place-holder }}', 'new_str')
print(val)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.