如何在 YAML 中打印带有双引号和空格的值?

How to print a value with double quotes and spaces in YAML?

我正在尝试将 Python 字典转储到 YAML,其中包含一些字符串作为值字段。

import yaml
str1 = "hello"
str2 = "world"
mystr = "\"" + str1 + str(" ") + str2 + "\""
mydict = {"a" : mystr}
f = open("temp.yaml", "w")
yaml.dump(mydict, f, default_flow_style = False, \
                    explicit_start = "---", explicit_end = "...", encoding = 'UTF-8')
f.close()

我得到的 YAML 是:

a: '"hello
 world"'

注意,值 "hello world" 溢出到下一行。 我使用的是 python 3.5,YAML 模块版本是 3.11

谁能告诉我如何使 YAML 看起来像下面这样?

a: "hello world"

代码有点草率,但它会给出你想要的结果。

global dict_keys

def mk_double_quote(dumper, data):
    if data in dict_keys:
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='')
    else:
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(str, mk_double_quote)

d = {'a': 'Hello World'}
dict_keys = set(d.keys())

f = open('temp.yaml', 'w')
yaml.dump(d, f, default_flow_style=False, encoding='utf-8')
f.close()

结果将如下所示:a: "Hello World"

如果您想精细控制哪个字符串使用双引号(或单引号),您应该使用 ruamel.yaml(免责声明:我是该包的作者)。它是 PyYAML 的改进版本,修复了 PyYAML 中许多长期存在的问题。

有了它你可以做:

import sys
import ruamel.yaml

mystr = ruamel.yaml.scalarstring.DoubleQuotedScalarString('hello world')
mydict = dict(a=mystr)

yaml = ruamel.yaml.YAML()
yaml.dump(mydict, sys.stdout)

得到:

a: "hello world"

如果您从 YAML 文档开始,事情就更简单了,您只需表明您想要保留这些多余的引号即可:

yaml_str = """\
a: "hello world"
"""

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)