问题描述
我想从使用 ruamel.yaml
加载的 YAML 文件中获取注释字符串.项目文档 缺少 API 参考,我找不到相关示例.访问评论的正确方法是什么?
I'd like to get the comment strings from a YAML file I loaded using ruamel.yaml
. The project documentation lacks an API reference and I can't find a relevant example. What's the right way to access the comments?
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?
推荐答案
库作者在 BitBucket 上的一个问题(2016 年 5 月 9 日):
The library author comments on this in an issue on BitBucket (May 9, 2016):
评论保存未稳定,例如如果映射的键和值不在同一行并且键(或键和值)有注释,我需要做一些事情.我最初的目标是保留现有的评论,而不是太多的操纵.
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.
通过一些实验,我确定了上述问题中提供的示例代码的以下工作:
Through some experimentation I determined the following works for the example code provided in the question above:
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)
这篇关于如何在 Python 中使用 ruamel.yaml 从 YAML 文件中获取注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!