gpt4 book ai didi

Python YAML 保留换行符而不添加额外的换行符

转载 作者:太空狗 更新时间:2023-10-29 22:29:57 34 4
gpt4 key购买 nike

我有一个与 this question 类似的问题我需要在 YAML 映射值字符串中插入换行符并且不想自己插入 \n。答案建议使用:

Data: |
Some data, here and a special character like ':'
Another line of data on a separate line

代替

Data: "Some data, here and a special character like ':'\n
Another line of data on a separate line"

还在末尾添加换行符,这是 Not Acceptable 。

我尝试使用 Data: > 但结果显示完全不同。在阅读 yaml 文件后,我一直在剥离最后的换行符,这当然有效,但并不优雅。有没有更好的方法来保留换行符而不在末尾添加额外的换行符

我正在使用 python 2.7 fwiw

最佳答案

如果您使用 | 这会使标量变成 literal block style scalar .但是 | 的默认行为是剪裁,这不会为您提供所需的字符串(因为它会留下最后的换行符)。

您可以通过附加 block chomping indicators 来“修改”| 的行为

Strip

Stripping is specified by the “-” chomping indicator. In this case, the final line break and any trailing empty lines are excluded from the scalar’s content.

Clip

Clipping is the default behavior used if no explicit chomping indicator is specified. In this case, the final line break character is preserved in the scalar’s content. However, any trailing empty lines are excluded from the scalar’s content.

Keep

Keeping is specified by the “+” chomping indicator. In this case, the final line break and any trailing empty lines are considered to be part of the scalar’s content. These additional lines are not subject to folding.

通过将 stripchomping 运算符“-”添加到“|”,您可以防止/去除最后的换行符:¹

import ruamel.yaml as yaml

yaml_str = """\
Data: |-
Some data, here and a special character like ':'
Another line of data on a separate line
"""

data = yaml.load(yaml_str)
print(data)

给出:

{'Data': "Some data, here and a special character like ':'\nAnother line of data on a separate line"}


¹ 这是使用 ruamel.yaml 完成的我是其中的作者。使用 PyYAML(其中 ruamel.yaml 是一个超集,在往返过程中保留注释和文字标量 block )应该会得到相同的结果。

关于Python YAML 保留换行符而不添加额外的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022588/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com