在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
当然,如果额外的行首空格会更有效一开始就不会生成。
我是一名优秀的程序员,十分优秀!