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

How can I get comments from a YAML file using ruamel.yaml in Python?(如何在 Python 中使用 ruamel.yaml 从 YAML 文件中获取注释?)
本文介绍了如何在 Python 中使用 ruamel.yaml 从 YAML 文件中获取注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想从使用 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 文件中获取注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)