简体   繁体   English

如何使用 ruamel.yaml 在 YAML 文件中保留或添加值周围的引号而不剥离注释作为副作用?

[英]How can I preserve or add quotes around values in a YAML file without stripping comments as a side effect using ruamel.yaml?

I am trying to generate a YAML file, which does not fall foul of the Norway problem described here: https://hitchdev.com/strictyaml/why/implicit-typing-removed/我正在尝试生成一个 YAML 文件,它不会违反此处描述的挪威问题: https ://hitchdev.com/strictyaml/why/implicit-typing-removed/

I am running ruamel.yaml 0.17.21 in python 3.8.我在 python 3.8 中运行 ruamel.yaml 0.17.21。

Here is the code I am running:这是我正在运行的代码:

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"""
)

Thanks to @Anthon and @JonSG for constructive feedback.感谢@Anthon 和@JonSG 的建设性反馈。 Based on that, I found this article How to correctly output strings with ruamel.yaml基于此,我找到了这篇文章How to correctly output strings with ruamel.yaml

My working solution is therefore:因此,我的工作解决方案是:

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"
"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM