如何从ruamel.yaml dump的输出中删除2个空格? [英] How to remove 2 spaces from the output of ruamel.yaml dump?

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

问题描述

yaml.indent(sequence = 4,offset = 2)的帮助下,输出是正确的,但是每行中都有多余的空间,我知道这是由于上面的indent函数所致.有什么方法可以从每行中删除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问题中获得帮助:

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("\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

当然,如果多余的行首空格会更有效 首先不会生成.

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

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆