在ruamel.yaml
(或 PyYAML)中没有选择或简单的方法来获得你想要的东西。
映射键的值description
是普通标量,您可能已将输出宽度设置为70
(或类似)以获得该结果。该值是一个普通样式的标量,可以在由非空格字符包围的任何空格上断开。
您可能考虑过使用块样式的文字标量,但尽管
description: |-
The is the first line of the sentence and then we continue
on to the second line but this line should be indented to match the
first line of the string.
几乎看起来相似,它实际上在该字符串中加载了两个额外的换行符。即使您在转储之前预处理该标量并在加载后对其进行后处理以尝试使用显式块缩进指示器也不会给您超过 9 个位置(因为它被限制为单个数字)并且您拥有的不止这些。
如果可以接受以下格式:
ResourceIndicators:
version: 1.0.0
name: This is the name
neType: Text
category: Text
description: |-
The is the first line of the sentence and then we continue
on to the second line but this line should be indented to
match the first line of the string.
你可以用一个小函数来做到这一点wrapped
:
import sys
import textwrap
import ruamel.yaml
from ruamel.yaml.scalarstring import PreservedScalarString
yaml_str = """\
ResourceIndicators:
version: 1.0.0
name: This is the name
neType: Text
category: Text
description: The is the first line of the sentence and then we continue
on to the second line but this line should be indented to match the
first line of the string.
"""
def wrapped(s, width=60):
return PreservedScalarString('\n'.join(textwrap.wrap(s, width=width)))
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
data['ResourceIndicators']['description'] = \
wrapped(data['ResourceIndicators']['description'])
yaml.dump(data, sys.stdout)
但请注意,加载后您必须用空格替换值中的换行符。
如果这不是一个选项,您需要创建一个具有特殊表示器的类“IndentedPlainString”来执行额外的缩进。