Python转储YAML在字符串周围使用双引号 [英] Python Dump YAML Using Double Quotes Around Strings

查看:1018
本文介绍了Python转储YAML在字符串周围使用双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3.5中,我将以下字典转储到.yaml文件中。

In Python 3.5, I have the following dictionary to be dumped into a .yaml file.

D = {'name':' mydata,值:{'x':1,'y':2,'z':3}}

当我运行时以下代码:

import ruamel
import ruamel.yaml as yaml
D={'name': 'mydata', 'value': {'x': 1, 'y': 2, 'z':3}}
yaml.round_trip_dump(D, open('my_yaml.yaml', 'w'),
                     default_flow_style=False, indent=4)

结果 my_yaml.yaml 如下所示:

name: mydata                                                                    
value:                                                                     
    z: 3                                                                     
    x: 1                                                                   
    y: 2

我的问题是,有方便吗在 mydata 周围写双引号的方法,即,代替 name:mydata ,它写为 name: mydata

My question is, is there a handy way to write double quotes around mydata, i.e., instead of name: mydata, it is written as name: "mydata"

推荐答案

有一种相对简单的方法: / p>

There is a relatively easy way to do this:

import sys
import ruamel.yaml

S = ruamel.yaml.scalarstring.DoubleQuotedScalarString
D = {'name': S('mydata'), 'value': {'x': 1, 'y': 2, 'z':3}}

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=4)
yaml.dump(D, sys.stdout)

使用YAML实例的最后三行是更新的操作方式:

that last three lines, using an instance of YAML, is the newer way of doing:

ruamel.yaml.round_trip_dump(D, sys.stdout, indent=4)

使用新的API,您可以为序列指定不同的缩进值。

Using the new API, you can give a different indent value for your sequences.

无论哪种方式,上面的代码都能为您提供:

Either way, the above gives you:

name: "mydata"
value:
    x: 1
    y: 2
    z: 3

使用 ruamel.yaml 的往返模式时,无需显式执行 default_flow_style = False

There is no need to explicitly do default_flow_style=False when using ruamel.yamls round-trip-mode.

DoubleQuotedScalarString 的子类) str 是用于存储 mydata 的方法,如果您加载了首选输出,同时又保留了引号:

The DoubleQuotedScalarString, a subclass of str, is what is used to store "mydata" if you load your preferred output, while preserving quotes:

yaml.preserve_quotes = True
data = yaml.load("""\
name: "mydata"
value:
    x: 1
    y: 2
    z: 3
""")
print(type(data['name']))

给出:

<class 'ruamel.yaml.scalarstring.DoubleQuotedScalarString'>

如果输出往返正确,检查数据结构<$总是一个好主意c $ c> ruamel.yaml 加载,无论是用于双引号,块样式文字标量,十六进制整数还是注释保留。

该库在后台做了很多工作其中没有文档,图书馆的作者可能太懒了,无法提供更多内容。

If your output round-trips correctly, it is always a good idea to inspect the data structure ruamel.yaml loads, whether it is for double quotes, block style literal scalars, hexadecimal ints or comment preservation.
The library does a lot behind the scenes for which there is no documentation, and the library's author is probably too lazy to provide more of it.

这篇关于Python转储YAML在字符串周围使用双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆