gpt4 book ai didi

python - 如何从 ruamel.yaml 转储的输出中删除 2 个空格?

转载 作者:太空宇宙 更新时间:2023-11-03 19:49:15 24 4
gpt4 key购买 nike

yaml.indent(sequence=4, offset=2)的帮助下,输出是正确的,但是每行都有额外的空间,我知道这是由于上面的缩进函数造成的。有什么方法可以删除每行中的 2 个额外空格(我不使用 strip())。

代码:

import sys
import ruamel.yaml

data = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]

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

以上代码的输出:

  - item: Food_eat
Food:
foodNo: 42536216
type: fruit
moreInfo:
- organic

所需输出:

- item: Food_eat
Food:
foodNo: 42536216
type: fruit
moreInfo:
- organic

P.S:我从这个 stackoverflow 问题中得到了帮助:How to safe_dump the dictionary and list into YAML?

最佳答案

与其说是缩进,不如说是序列的偏移量项目指标。该偏移量是在项目之前的空间内获取的如果根节点是一个列表,这会给出正确的 YAML,但它看起来次优。

我一直在考虑解决这个问题,但还没有想出一个好的解决方案。直到我您是否需要对输出进行后处理,这很容易完成:

import sys
import ruamel.yaml

data = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]

def strip_leading_double_space(stream):
if stream.startswith(" "):
stream = stream[2:]
return stream.replace("\n ", "\n")
# you could also do that on a line by line basis
# return "".join([s[2:] if s.startswith(" ") else s for s in stream.splitlines(True)])


yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
print('# < to show alignment')
yaml.dump(data, sys.stdout, transform=strip_leading_double_space)

给出:

# < to show alignment
- item: Food_eat
Food:
foodNo: 42536216
type: fruit
moreInfo:
- organic

当然,如果额外的行首空格会更有效一开始就不会生成。

关于python - 如何从 ruamel.yaml 转储的输出中删除 2 个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936237/

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