用doc purpos的注释进行YAML解析

2024-05-19 08:57:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在YAML上添加注释来自动生成YAML文件的文档,就像docstrings对Python所做的那样。在

因此,我正在寻找一个python解析器,它能够:

  • 尊重事物的秩序
  • 包括评论

我的研究表明拉梅尔亚姆勒. 但除非我没有得到所有的东西,否则它不允许在加载注释时访问YAML对象。它只允许在加载期间转储这些注释。在

你知道吗,什么能满足我的需要?在


Tags: 文件对象文档解析器yaml评论秩序事物
0条回答
网友
1楼 · 发布于 2024-05-19 08:57:50

ruamel.yaml中,YAML()实例只将信息保存到 负荷响应。丢弃你的YAML文档。它不允许您访问 注释,因为它不将它们存储在实例上。在

正如您所指出的,ruamel.yaml可以转储注释,因此它们必须这样做 在某个地方,它们确实是:依附于对象层次结构 由YAML.load()创建。你需要做的是递归行走 为获取附加注释而加载的数据结构。在

对于当前附加注释的方式,可以使用以下类似的方法:

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})")

它给出了:

^{pr2}$

相关问题 更多 >

    热门问题