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

How can I get comments from a YAML file using ruamel.yaml in Python?

我想从使用 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)