gpt4 book ai didi

python - 如何使用 ruamel.yaml 正确缩进序列?

转载 作者:太空狗 更新时间:2023-10-30 00:38:22 28 4
gpt4 key购买 nike

有以下数据

from ruamel import yaml
data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

我得到的序列缩进不正确

>>> print yaml.round_trip_dump(data)
1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42

在 Notepad++ 上无法折叠。然而,通过适当的缩进它可以工作:

差:

Bad Indent

好:

Good Indent

我尝试使用 block_seq_indent=2:

>>> print yaml.round_trip_dump(data, block_seq_indent=2)
1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42

我该如何解决这个问题?

最佳答案

ruamel.yaml 文档,虽然通常缺乏,但对 offset 说了以下内容缩进中的破折号:

If the offset equals sequence, there is not enough room for the dash and the space that has to follow it. In that case the element itself would normally be pushed to the next line (and older versions of ruamel.yaml did so). But this is prevented from happening. However the indent level is what is used for calculating the cumulative indent for deeper levels and specifying sequence=3 resp. offset=2, might give correct, but counter intuitive results.

It is best to always have sequence >= offset + 2 but this is not enforced. Depending on your structure, not following this advice might lead to invalid output.

默认情况下,缩进(对于映射和序列)等于 2,如果您这样做:

import sys
from ruamel import yaml

data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

yml = yaml.YAML()
yml.indent(mapping=2, sequence=4, offset=2)
yml.dump(data, sys.stdout)

你得到:

1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42

使用您在问题中使用的旧 API,您不能以简单的方式对映射和序列进行不同的缩进(您需要子类化发射器,并且在 __init__ 之后基类,设置值)。对于旧版本的 ruamel.yaml,这是根本不可能的。

这仅适用于默认(往返,即 typ='rt')转储程序,但适用于普通的 Python dict resp。 list(例如来自 YAML(typ='safe').load(....))和在执行 YAML().load(....)

时使用了更多复杂的子类

(以上需要ruamel.yaml>=0.15.30)

关于python - 如何使用 ruamel.yaml 正确缩进序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44388701/

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