用ruam在yaml中插入节点

2024-09-29 17:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印以下版式:

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']

我试过其他组合,但没用?在


Tags: 工具代码httpyaml节点contenttoolsextra
2条回答

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

所以与其这样做:

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

你应该做的是:

^{pr2}$

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

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

一旦加载了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到它:

^{pr2}$

如果打印出数据结构,则会得到有效的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

相关问题 更多 >

    热门问题