【问题标题】:inserting node in yaml with ruamel使用 ruamel 在 yaml 中插入节点
【发布时间】:2017-10-13 20:26:08
【问题描述】:

我想打印以下布局:

extra: identifiers: biotools: - http://bio.tools/abyss

我正在使用此代码添加节点:

yaml_file_content['extra']['identifiers'] = {}
yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']

但是,相反,我得到了这个输出,它将工具封装在 [] 中:

extra: identifiers: biotools: ['- http://bio.tools/abyss']

我尝试了其他组合但没有奏效?

【问题讨论】:

    标签: python pyyaml ruamel.yaml


    【解决方案1】:

    - http://bio.tools/abyss 中的破折号表示一个序列元素,如果您以块样式转储 Python 列表,则会在输出中添加。

    所以不要这样做:

    yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']
    

    你应该这样做:

    yaml_file_content['extra']['identifiers']['biotools'] = ['http://bio.tools/abyss']
    

    然后使用以下命令强制以块样式输出所有复合元素:

    yaml.default_flow_style = False
    

    如果您想要更细粒度的控制,请创建一个ruamel.yaml.comments.CommentedSeq 实例:

    tmp = ruamel.yaml.comments.CommentedSeq(['http://bio.tools/abyss'])
    tmp.fa.set_block_style()
    yaml_file_content['extra']['identifiers']['biotools'] = tmp
    

    【讨论】:

    • 谢谢,@Anthon。它工作得很好。如果其中一些示例直接转到文档以提高库的可用性,那就太好了。
    • 如果此答案解决了您的问题,请考虑通过单击答案旁边的 ✔(复选标记)接受。这就是其他人知道您的问题已解决的方式,而无需阅读 cmets。它还改变了问题的外观和列表中的这个答案。如果出现更好的答案,您可以随时更改已接受的答案。
    【解决方案2】:

    一旦你加载了一个 YAML 文件,它就不再是“yaml”了;它现在是一个 Python 数据结构,biotools 键的内容是 list

    >>> import ruamel.yaml as yaml
    >>> data = yaml.load(open('data.yml'))
    >>> data['extra']['identifiers']['biotools']
    ['http://bio.tools/abyss']
    

    与任何其他 Python 列表一样,您可以append 对其:

    >>> data['extra']['identifiers']['biotools'].append('http://bio.tools/anothertool')
    >>> data['extra']['identifiers']['biotools']
    ['http://bio.tools/abyss', 'http://bio.tools/anothertool']
    

    如果你打印出数据结构,你会得到有效的 YAML:

    >>> print( yaml.dump(data))
    extra:
      identifiers:
        biotools: [http://bio.tools/abyss, http://bio.tools/anothertool]
    

    当然,如果由于某种原因你不喜欢那个列表表示,你也可以得到语法上等价的:

    >>> print( yaml.dump(data, default_flow_style=False))
    extra:
      identifiers:
        biotools:
        - http://bio.tools/abyss
        - http://bio.tools/anothertool
    

    【讨论】:

    • 我已经编辑了我的问题,问题出在输出上,当我想用​​- http://bio.tools/abyss@larsks 换行时,我的工具名称中使用了 []
    • 我不确定你是否完全理解了我的回答,但我添加了一些进一步的例子来试图澄清事情。
    • dump() got an unexpected keyword argument 'default_flow_style' 我正在使用 from ruamel.yaml import YAML 和 jinja2 的插件
    • ruamel.yaml.__version__ 的值是多少?您能否在问题中显示您用于加载 YAML 文档的实际代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2020-05-23
    • 2019-09-08
    • 2021-05-10
    相关资源
    最近更新 更多