我有一个 yaml 文档,如下所示。
doc="""
... network-interface: >
... auto $(intf)
... iface $(intf) inet static
... address $(addr)
... network $(net)
... netmask $(mask)
... """
我正在加载这个文档并获取一个 python 字典。我正在尝试将此文档转换回原始文档,并且收到“\n
”字符。
ydict = yaml.load(doc)
ndoc = yaml.dump(ydict)
print ndoc
{network-interface: "auto $(intf)\n iface $(intf) inet static\n address $(addr)\n\
\ network $(net)\n netmask $(mask)\n"}
print yaml.dump(ydict, default_flow_style=False)
network-interface: "auto $(intf)\n iface $(intf) inet static\n address $(addr)\n\
\ network $(net)\n netmask $(mask)\n"
如何在没有“\n
”的情况下取回原始文档。
您使用 folded block style 指定字符串,但是以 'iface' 开头的行及其后的额外缩进会导致它得到“硬”换行符。
如果对齐这些线:
import yaml
doc="""
network-interface: >
auto $(intf)
iface $(intf) inet static
address $(addr)
network $(net)
netmask $(mask)
"""
ydict = ruamel.yaml.load(doc, Loader=ruamel.yaml.RoundTripLoader)
ndoc = ruamel.yaml.dump(ydict, Dumper=ruamel.yaml.RoundTripDumper)
ydict = ruamel.yaml.load(doc)
ndoc = ruamel.yaml.dump(ydict)
print ndoc
您将得到:
{network-interface: 'auto $(intf) iface $(intf) inet static address $(addr) network
$(net) netmask $(mask)
'}
如果您希望输出 YAML 更接近您的输入,您应该考虑使用 ruamel.yaml (我是作者)并使用 literal style (|
):
import ruamel.yaml
doc="""
network-interface: |
auto $(intf)
iface $(intf) inet static
address $(addr)
network $(net)
netmask $(mask)
"""
ydict = ruamel.yaml.load(doc, Loader=ruamel.yaml.RoundTripLoader)
ndoc = ruamel.yaml.dump(ydict, Dumper=ruamel.yaml.RoundTripDumper)
print ndoc
给你:
network-interface: |
auto $(intf)
iface $(intf) inet static
address $(addr)
network $(net)
netmask $(mask)
我是一名优秀的程序员,十分优秀!