【问题标题】:How to update a YML file with | seperator如何使用 | 更新 YAML 文件分隔器
【发布时间】:2021-03-15 02:40:56
【问题描述】:

我有一个看起来像这样的 .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)

【问题讨论】:

  • 你不能把它当作一个 txt 文件并附加任何你想要的东西吗?确保你当然保持正确的缩进......或者这是一个更大的文件,这会变得棘手
  • @DerekEden 这根本不是一个大文件,但我想带上正确的缩进不是很复杂,|等等,如果我们将其视为 txt,然后将其保存为 yml。或者我错过了什么

标签: python python-3.x yaml pyyaml


【解决方案1】:

| 不是 分隔符。它是块标量的标头,意味着examples 的值是带有内容"- hey\n- hello\n- hi\n- hello there\n" 的标量。要附加具有相同语义结构的另一个序列项,您需要这样做

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

完整的工作示例:

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': "- first\n- second"})

yaml.safe_dump(cur_yaml, sys.stdout)

这个输出

nlu:
- examples: '- hey

    - hello

    - hi

    - hello there

    '
  intent: greet
- examples: '- first

    - second

    '
  intent: name

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

从那里的答案中得出的结论是,要保留样式,您需要在较低级别修改 YAML 文件的内容,以便 Python 不会忘记原始样式。我已经在this answer 中展示了如何做到这一点。使用那里定义的函数,您可以像这样获得所需的输出:

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

这会将您的 YAML 输入转换为

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

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2015-04-17
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2021-10-07
    • 2021-05-02
    • 2019-09-08
    • 2023-02-11
    相关资源
    最近更新 更多