How to remove 2 spaces from the output of ruamel.yaml dump?(如何从 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 个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 ruamel.yaml 转储的输出中删除 2 个空格?
基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01