使用 ruamel.yaml 从 YAML 获取评论时出现问题
Issue in getting the comments from YAML using ruamel.yaml
代码:
import ruamel.yaml
yaml_str = """\
# comments start
a: 52
# comment for a
b: 50
# comment for b
c: 50
# comment for c
d:
# comment for d
e: 60
# comment for e
f: 70
# comment for f
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
print(data.ca.comment)
print(data.ca.items)
输出:
[None, [CommentToken('# comments start\n', line: 0, col: 0)]]
{'a': [None, None, CommentToken('\n# comment for a\n', line: 2, col: 0), None], 'b': [None, None, CommentToken('\n# comment for b\n', line: 4, col: 0), None], 'c': [None, None, CommentToken('\n# comment for c\n', line: 6, col: 0), None], 'd': [None, None, None, [CommentToken('# comment for d\n', line: 8, col: 4)]]}
问题:
- 为什么它不显示与键
e
和 f
有关的评论?
- 例如,根据关键字 say 检索评论的正确方法是什么。如何获取键
e
( # comment for e
) 的评论?
在 ruamel.yaml 中,大多数评论都附在字典(或列表)上,例如
包含键(或元素)的结构,其后是注释
发生了。
要获取键 e
和 f
之后的注释,您需要查看字典
这是 d
:
的值
print(data['d'].ca.items)
print('comment post commment for "e":', repr(data['d'].ca.get('e', 2).value))
给出:
{'e': [None, None, CommentToken('\n # comment for e\n', line: 10, col: 3), None], 'f': [None, None, CommentToken('\n # comment for f\n', line: 12, col: 3), None]}
comment post commment for "e": '\n # comment for e\n'
请注意e
的注释以换行开头,表示没有行尾注释
代码:
import ruamel.yaml
yaml_str = """\
# comments start
a: 52
# comment for a
b: 50
# comment for b
c: 50
# comment for c
d:
# comment for d
e: 60
# comment for e
f: 70
# comment for f
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
print(data.ca.comment)
print(data.ca.items)
输出:
[None, [CommentToken('# comments start\n', line: 0, col: 0)]]
{'a': [None, None, CommentToken('\n# comment for a\n', line: 2, col: 0), None], 'b': [None, None, CommentToken('\n# comment for b\n', line: 4, col: 0), None], 'c': [None, None, CommentToken('\n# comment for c\n', line: 6, col: 0), None], 'd': [None, None, None, [CommentToken('# comment for d\n', line: 8, col: 4)]]}
问题:
- 为什么它不显示与键
e
和f
有关的评论? - 例如,根据关键字 say 检索评论的正确方法是什么。如何获取键
e
(# comment for e
) 的评论?
在 ruamel.yaml 中,大多数评论都附在字典(或列表)上,例如 包含键(或元素)的结构,其后是注释 发生了。
要获取键 e
和 f
之后的注释,您需要查看字典
这是 d
:
print(data['d'].ca.items)
print('comment post commment for "e":', repr(data['d'].ca.get('e', 2).value))
给出:
{'e': [None, None, CommentToken('\n # comment for e\n', line: 10, col: 3), None], 'f': [None, None, CommentToken('\n # comment for f\n', line: 12, col: 3), None]}
comment post commment for "e": '\n # comment for e\n'
请注意e
的注释以换行开头,表示没有行尾注释