我正在尝试使用ruamel.yaml将python字典写入yaml文件。我需要显式引用一些字符串,所以我将它们传递给ruamel.yaml.scalarstring.DoubleQuotedScalarString,它在输出中用双引号将它们括起来。但是,包含在多行中的字符串在输出中包含\字符。我如何防止这种情况发生?
在将字符串传递给ruamel.yaml.scalarstring.DoubleQuotedScalarString并将其替换为'‘之后,我尝试使用正则表达式搜索\,但这不起作用。我认为这些字符是在转储时添加的。
S = ruamel.yaml.scalarstring.DoubleQuotedScalarString
string = "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."
st = S(string)
data = {'key': st}
f = open('./yam.yaml', 'w')
yaml= YAML()
yaml.default_flow_style = False
yaml.indent(offset = 2, sequence = 4, mapping = 2)
yaml.dump(data, f)期望值:
key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."实际:
key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise\
\ and quantify the various aspects of nocturnal sleep problems in Parkinson's disease\
\ (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."发布于 2019-07-26 00:42:46
您所看到的是由换行引起的,它试图将输出中行的长度限制为缺省值80个字符。
如果您可以接受更大的输出,那么只需将yaml.width设置为更大的值:
import sys
import ruamel.yaml
YAML = ruamel.yaml.YAML
S = ruamel.yaml.scalarstring.DoubleQuotedScalarString
string = "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."
st = S(string)
data = {'key': st}
yaml= YAML()
yaml.width = 2048
yaml.default_flow_style = False
yaml.indent(offset = 2, sequence = 4, mapping = 2)
yaml.dump(data, sys.stdout)这就给出了:
key: "The Parkinson's Disease Sleep Scale-Validation (PDSS-2) is a scale used to characterise and quantify the various aspects of nocturnal sleep problems in Parkinson's disease (PD). The PDSS-2 is a revised version of the Parkinson's Disease Sleep Scale (PDSS)."https://stackoverflow.com/questions/57205881
复制相似问题