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

时间:2023-04-16
本文介绍了如何从 ruamel.yaml 转储的输出中删除 2 个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

With the help of yaml.indent(sequence=4, offset=2) the output is correct but there is extra space coming in each line and I know it is due to above indent function. Is there any way to remove the 2 extra spaces from each line(I don't wont to use 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

PS:我从这个 stackoverflow 问题中得到了帮助:如何将字典和列表安全转储到 YAML 中?

P.S: I have taken help from this stackoverflow question by me: How to safe_dump the dictionary and list into YAML?

推荐答案

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

It is not so much the indent, as well as the offset of the sequence item indicator. This offset is taken within the space before the item and if the root node is a list, this gives correct YAML, but it looks sub-optimal.

我一直在寻找解决这个问题,但没有想出一个好的解决方案.直到我您是否必须对输出进行后处理,这很容易完成:

I have been looking at fixing this, but have not come up with a good solution. Until I do you'll have to post-process your output, which can be easily done:

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("
  ", "
")
    # 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

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

Of course it would be more efficient if the extra start-of-line spaces would not be generated in the first place.

这篇关于如何从 ruamel.yaml 转储的输出中删除 2 个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 yamltodb 将 YAML 数据转换为数据框 下一篇:GAE python中的YAML文件url和脚本

相关文章