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中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01