有没有一种方法可以在加载后使用ruamel.yaml检索YAML文档头部的注释?
例如:
yaml_str = """\
# comment at head of document
date: 20210326 # comment about key-pair
"""我知道如何检索date的评论
from ruamel.yaml import YAML
yml = YAML(typ='rt')
data = yml.load(yaml_str)
comments = data.ca.items.get('date')或者any other field in the document,但不是最初的评论。
发布于 2021-03-27 00:45:36
目前还没有获取此数据的方法。
你在一开始找不到评论的原因,是因为它的处理方式与所有其他评论不同。当在输入流中看到其他注释时,可以在解析的数据节点上附加注释,但在任何数据之前的注释当然不是这种情况。
您可以检索这些注释,但应该确保检查ruamel.yaml的版本,因为对附加注释的方式进行了更改have been announced
import ruamel.yaml
yaml_str = """\
# comment at head of document
# another one after empty line
date: 20210326 # comment about key-pair
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
if ruamel.yaml.version_info <= (0, 17, 0):
comments = [x.value for x in data.ca.comment[1]]
else:
raise NotImplementedError
print(comments)这就给出了:
['# comment at head of document\n\n', '# another one after empty line\n'].ca的.comment属性几乎肯定会在将来的版本中消失,所以您可以只使用try-except。将空行作为额外的换行符对前面的注释进行排序,格式也会发生变化,但在这种情况发生时,很可能会获得稳定的访问方法(因此,您不需要多次升级代码)。
发布于 2021-03-27 00:18:32
这就是我发现的检查对象的方法:
>>> data.ca.comment[1][0].value
'# comment at head of document\n'https://stackoverflow.com/questions/66820321
复制相似问题