gpt4 book ai didi

python - 如何在 Python 中使用 ruamel.yaml 从 YAML 文件中获取注释?

转载 作者:太空狗 更新时间:2023-10-30 01:20:36 24 4
gpt4 key购买 nike

我想从使用 ruamel.yaml 加载的 YAML 文件中获取评论字符串。 project documentation缺少 API 引用,我找不到相关示例。访问评论的正确方法是什么?

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?

最佳答案

库作者在 an issue on BitBucket 中对此发表评论(2016 年 5 月 9 日):

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.

通过一些实验,我确定了上述问题中提供的示例代码的以下工作:

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 - 如何在 Python 中使用 ruamel.yaml 从 YAML 文件中获取注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com