如何使用|seperator更新YML文件



我有一个.yml文件,如下所示。

nlu:
- intent: greet
examples: |
- hey
- hello
- hi
- hello there

现在我想更新这个文件,从python中添加一个新的意图和示例。但是,由于每当我更新文件时,它都有一个|,所以文件的对齐方式会变得一团糟。

像这样

with open('nlu.yml', 'r') as yamlfile:
cur_yaml = yaml.safe_load(yamlfile)
cur_yaml['nlu'].append({ 'intent': 'name', 'examples': ['first', 'second']})
with open('nlu.yml', 'w') as yamlfile:
yaml.safe_dump(cur_yaml, yamlfile)

|不是分隔符。它是块标量的头,意味着examples的值是内容为"- heyn- hellon- hin- hello theren"的标量。要附加另一个具有相同语义结构的序列项,您需要执行

with open('nlu.yml', 'r') as yamlfile:
cur_yaml = yaml.safe_load(yamlfile)
cur_yaml['nlu'].append({ 'intent': 'name', 'examples': "- firstn- secondn"})

完整的工作示例:

import yaml, sys
input = """
nlu:
- intent: greet
examples: |
- hey
- hello
- hi
- hello there
"""
cur_yaml = yaml.safe_load(input)
cur_yaml['nlu'].append({ 'intent': 'name', 'examples': "- firstn- second"})
yaml.safe_dump(cur_yaml, sys.stdout)

此输出

nlu:
- examples: '- hey
- hello
- hi
- hello there
'
intent: greet
- examples: '- first
- second
'
intent: name

现在,虽然这个输出具有正确的YAML语义,但您可能不喜欢它的格式。有关为什么会发生这种情况的深入解释,请参阅此问题。

答案是,为了保留样式,您需要在较低级别上修改YAML文件的内容,这样Python就不会忘记原始样式。我已经在这个答案中展示了如何做到这一点。使用那里定义的函数,你可以达到你想要的输出,如下所示:

append_to_yaml("input.yaml", "output.yaml", [
AppendableEvents(["nlu"],
[MappingStartEvent(None, None, True), key("intent"), key("name"),
key("examples"), literal_value("- hello theren- general Kenobin"),
MappingEndEvent()])])

这将把您的YAML输入转换为

nlu:
- intent: greet
examples: |
- hey
- hello
- hi
- hello there
- intent: name
examples: |
- hello there
- general Kenobi

最新更新