2017-10-13 103 views
1

我想有印刷布局如下:插入节点YAML与ruamel

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

我尝试了其他组合,但没有工作?

回答

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 
+0

谢谢,@Anthon。它工作得很好。如果这些例子中的一些直接用于文档来提高图书馆的可用性,那将是非常好的。 – ypriverol

+1

如果此答案解决了您的问题,请通过单击答案旁边的✔(复选标记)来考虑*接受*。这是其他人知道你的问题已经解决的方式,没有阅读评论。它还会在列表中更改问题的外观和此答案。如果有更好的答案出现,您可以随时更改接受的答案。 – Anthon

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] 

当然,如果由于某种原因你不喜欢这样的名单表示你还可以得到在S yntactically相当于:

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

我编辑了我的问题,问题是与输出,即在我的工具名称中使用[]时,我想用' - http:// bio.tools/abyss' @larsks换行 – ypriverol

+0

我不确定你已经完全明白我的答案,但我已经添加了一些更多的例子来澄清事情。 – larsks

+0

'dump()得到了一个意想不到的关键字参数'default_flow_style''我使用'from ruamel.yaml import YAML'和jinja2的插件 – ypriverol