如何从 ruamel.yaml 转储的输出中删除 2 个空格?
How to remove 2 spaces from the output of ruamel.yaml dump?
在 yaml.indent(sequence=4, offset=2) 的帮助下,输出是正确的,但每行都有额外的 space我知道这是由于上述缩进功能。有没有办法从每行中删除 2 个额外的 spaces(我不会使用 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:我从这个 Whosebug 问题中得到了帮助:
与其说是缩进,不如说是序列的偏移量
项指标。这个偏移量是在item之前的space内取的
如果根节点是一个列表,这会给出正确的 YAML,但它看起来
次优。
我一直在考虑解决这个问题,但还没有找到好的解决方案。直到我
您是否必须 post 处理您的输出,这很容易完成:
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
当然如果额外的行首spaces会更有效率
本来就不会生成。
在 yaml.indent(sequence=4, offset=2) 的帮助下,输出是正确的,但每行都有额外的 space我知道这是由于上述缩进功能。有没有办法从每行中删除 2 个额外的 spaces(我不会使用 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:我从这个 Whosebug 问题中得到了帮助:
与其说是缩进,不如说是序列的偏移量 项指标。这个偏移量是在item之前的space内取的 如果根节点是一个列表,这会给出正确的 YAML,但它看起来 次优。
我一直在考虑解决这个问题,但还没有找到好的解决方案。直到我 您是否必须 post 处理您的输出,这很容易完成:
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
当然如果额外的行首spaces会更有效率 本来就不会生成。