我正在尝试使用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)."
答案 0 :(得分:0)
您看到的是由换行引起的,该换行试图将输出中的行长度限制为默认的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)."