import sys
import ruamel.yaml
from ruamel.yaml.tokens import CommentToken
yaml_str = """\
a:
b:
- elem1 # this is the first comment
- elem2 # this is the second comment
c:
d: 42 # this is not the 42nd comment
"""
def extract_from_token(tl):
assert isinstance(tl, list)
for t in tl:
if t is None:
continue
yield t.start_mark.line, t.value
def get_yaml_comments(d):
if isinstance(d, dict):
if d.ca.comment is not None:
for l, c in extract_from_token(d.ca.comment):
yield l, c
for key, val in d.items():
for l, c in get_yaml_comments(val):
yield l, c
if key in d.ca.items:
for l, c in extract_from_token(d.ca.items[key]):
yield l, c
elif isinstance(d, list):
if d.ca.comment is not None:
for l, c in extract_from_token(d.ca.comment):
yield l, c
for idx, item in enumerate(d):
for l, c in get_yaml_comments(item):
yield l, c
if idx in d.ca.items:
for l, c in extract_from_token(d.ca.items[idx]):
yield l, c
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
for line, comment in get_yaml_comments(data):
print(f"{comment!r} ({line})")
在
ruamel.yaml
中,YAML()
实例只将信息保存到 负荷响应。丢弃你的YAML文档。它不允许您访问 注释,因为它不将它们存储在实例上。在正如您所指出的,
ruamel.yaml
可以转储注释,因此它们必须这样做 在某个地方,它们确实是:依附于对象层次结构 由YAML.load()
创建。你需要做的是递归行走 为获取附加注释而加载的数据结构。在对于当前附加注释的方式,可以使用以下类似的方法:
它给出了:
^{pr2}$相关问题 更多 >
编程相关推荐