如何在Python中使用ruamel.yaml从YAML文件中获取注释?

前端之家收集整理的这篇文章主要介绍了如何在Python中使用ruamel.yaml从YAML文件中获取注释?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想从使用ruamel.yaml加载的YAML文件获取注释字符串. project documentation缺少API参考,我找不到相关的例子.访问评论的正确方法是什么?

import ruamel.yaml

yaml = """\
%YAML 1.2
---
# C1
a: # C2
  # C3
  # C4
  b: 1 # C5
  c: # A comment here will not be parsed properly by ruamel.yaml v0.11.14
  - abc # C6
  - xyz # C7
  # C8
# C9
"""

loaded = ruamel.yaml.round_trip_load(yaml)

# Now what?
最佳答案
图书馆作者于an issue on BitBucket(2016年5月9日)对此发表评论

The comment preservation has not stabilized,e.g. I need to do something if the key and value of a mapping are not on the same line and the key (or both key and value) have a comment. And my initial target was preservation of existing comments,not so much manipulation.

通过一些实验,我确定了上述问题中提供的示例代码的以下工作:

print('Comment 1: ' + loaded.ca.comment[1][0].value)
print('Comment 2: ' + loaded.ca.items['a'][2].value)
print('Comment 3: ' + loaded.ca.items['a'][3][0].value)
print('Comment 4: ' + loaded.ca.items['a'][3][1].value)
print('Comment 5: ' + loaded['a'].ca.items['b'][2].value)
print('Comment 6: ' + loaded['a']['c'].ca.items[0][0].value)
print('Comment 7: ' + loaded['a']['c'].ca.items[1][0].value)
print('Comment 8: ' + loaded['a']['c'].ca.end[0].value)
print('Comment 9: ' + loaded['a']['c'].ca.end[1].value)
原文链接:https://www.f2er.com/python/438585.html

猜你在找的Python相关文章