如何使用Ruamel.yaml在某些数据之前添加空白行

编程入门 行业动态 更新时间:2024-10-28 00:15:52
本文介绍了如何使用Ruamel.yaml在某些数据之前添加空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我似乎无法弄清楚如何使用Ruamel.yaml在数据之间添加空白行.

I can't seem to figure out how I can add a blank line between data using Ruamel.yaml.

假设我有数据:

--- a: 1 b: 2

我需要添加到此内容中,以便:

I need to add to this so that I will have:

--- a: 1 b: 2 c: 3

我知道空白行是作为CommentToken实现的:

I understand that the blank line is implemented as a CommentToken:

Comment(comment=None, items={'data': [None, None, CommentToken(value=u'\n\n'), None], 'b': [None, None, CommentToken(value=u'\n\n'), None]})

我不知道如何操纵这种结构.

What I don't know is how to manipulate that structure.

推荐答案

该Comment对象不是来自您提供的输入,因为data不是映射中的键,应为a:

That Comment object is not from the input that you give, as data is not a key in your mapping, that should be a:

import ruamel.yaml yaml_strs = [ """\ --- a: 1 b: 2 """, """\ --- a: 1 b: 2 c: 3 """] for yaml_str in yaml_strs: data = ruamel.yaml.round_trip_load(yaml_str) print(data.ca)

给予:

Comment(comment=None, items={'a': [None, None, CommentToken(), None]}) Comment(comment=None, items={'a': [None, None, CommentToken(), None], 'b': [None, None, CommentToken(), None]})

比较上面的评论应该使您对尝试的方法有所了解:

comparing the above comments should give you an idea of what to try:

import sys import ruamel.yaml yaml_str = """\ --- a: 1 b: 2 """ data = ruamel.yaml.round_trip_load(yaml_str) data['c'] = 3 ct = data.ca.items['a'][2] data.ca.items['b'] = [None, None, ct, None] ruamel.yaml.round_trip_dump(data, sys.stdout)

给出:

a: 1 b: 2 c: 3

CommentToken ct也可以从头开始构建:

The CommentToken ct can also be constructed from scratch:

ct = ruamel.yaml.tokens.CommentToken('\n\n', ruamel.yaml.error.CommentMark(0), None)

原样,例如在ruamel.yamlments.CommentedBase.yaml_set_start_comment()中完成.

as is, e.g. done in ruamel.yamlments.CommentedBase.yaml_set_start_comment().

CommentMark()的0参数是注释缩进的距离,在空行的情况下这并不重要,但仍需要提供.

The 0 parameter to CommentMark() is how far the comment is indented, which is not important in case of empty lines, but still needs to be provided.

更多推荐

如何使用Ruamel.yaml在某些数据之前添加空白行

本文发布于:2023-06-03 08:57:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/470188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   空白   数据   在某些   yaml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!