python-3.x 在使用ruamel.yaml时,如何在YAML文件的值周围保留或添加引号,而又不会产生去掉注解的副作用?

zc0qhyus  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(210)

我正在尝试生成一个YAML文件,它不会与这里描述的Norway问题相冲突:https://hitchdev.com/strictyaml/why/implicit-typing-removed/
我在python 3.8中运行ruamel.yaml0.17.21。
下面是我正在运行的代码:

import sys
from ruamel.yaml import YAML, round_trip_dump

data = [
    [1, """first value""", "first comment"],
    [2, '"second value"', "second comment"],
    ["abc", "None", 'this is a "comment"'],
    ["""def1""", "None", 'this is a "comment"'],
]
yaml = YAML()
yaml.preserve_quotes = True
code = yaml.load(
    """\
    en:
    """
)
for i, item in enumerate(data):
    code.insert(i + 1, str(item[0]), "" + str(item[1]) + "", comment=item[2])

print("\nthis strips quotes; but preserves comments:")
yaml.dump(code, sys.stdout)

print("\nthis preserves quotes; but strips comments:")
round_trip_dump(code, sys.stdout, default_style="'")

print("\ndesired result:")
print(
    "'en':\n
    '1': 'first value'  # first comment\n
    '2': 'second value' # second comment\n
    'abc': 'None' # this is a ""comment""\n
    'def1': 'None' # this is a ""comment"""
)
e4yzc0pl

e4yzc0pl1#

感谢@Anthon和@JonSG的建设性反馈,基于此,我找到了这篇文章How to correctly output strings with ruamel.yaml
因此,我的工作解决办法是:

import sys
from ruamel.yaml import YAML, scalarstring

DQ = scalarstring.DoubleQuotedScalarString

data = [
    [1, """first value""", "first comment"],
    [2, '"second value"', "second comment"],
    ["abc", "None", 'this is a "comment"'],
    ["""def1""", "None", 'this is a "comment"'],
]
yaml = YAML()
code = yaml.load(
    """\
    en:
    """
)
for i, item in enumerate(data):
    code.insert(i + 1, DQ(item[0]), DQ(str(item[1])), comment=item[2])

yaml.dump(code, sys.stdout)

"""
which produces:

en:
"1": "first value"  # first comment
"2": "\"second value\"" # second comment
"abc": "None" # this is a "comment"
"def1": "None" # this is a "comment"
"""

相关问题