1

我想打印以下布局:

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

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

4

2 回答 2

1

加载 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
于 2017-10-13T20:47:43.637 回答
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
于 2017-10-13T22:11:54.283 回答