rtn*_*pro 2 string yaml dump pyyaml empty-list
我已经添加了折叠字符串的表示符,如Python中的任何yaml库中提到的文字字符串,支持将长字符串转储为块文字或折叠块?.我还添加了representer来在转储的yaml内容中以块样式打印列表.
但问题是当字符串为空时,即""或列表为空时,它们在转储的YAML内容中以非块样式出现.
如何强制pyyaml转储器输出带有">"或"|"的空字符串 生成的YAML内容中的块样式中的flow_style = False的样式和空列表?
经过一些研究,我可以使用Pyyaml在YAML文件中将空字符串转储为块文字(样式在'|>'中).我的工作部分基于Python中的任何yaml库,它支持将长字符串转储为块文字或折叠块?.
import yaml
from yaml.emitter import Emitter, ScalarAnalysis
class MyEmitter(Emitter):
def analyze_scalar(self, scalar):
# Empty scalar is a special case.
# By default, pyyaml sets allow_block=False
# I override this to set allow_block=True
if not scalar:
return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
allow_flow_plain=False, allow_block_plain=True,
allow_single_quoted=True, allow_double_quoted=True,
allow_block=True)
return super(MyEmitter, self).analyze_scalar(scalar)
# And I subclass MyDumper from MyEmitter and yaml.Dumper
class MyDumper(yaml.Dumper, MyEmitter):
pass
class folded_unicode(unicode): pass
class literal_unicode(unicode): pass
def folded_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)
# I test it now
d = {'foo': {'folded': folded_unicode(''), 'literal': literal_unicode('')}}
print yaml.dump(d, Dumper=MyDumper)
Run Code Online (Sandbox Code Playgroud)
输出:
foo:
folded: >
literal: |
Run Code Online (Sandbox Code Playgroud)
但是,我无法找到以块样式转储空列表的方法.为此,我试图弄乱yaml/emitter.py并意识到我需要一个非空列表以块样式转储它.
无论如何,这种努力并没有白费,而是非常令人兴奋:)我希望有人可能会觉得这很有用或者可能有分享的东西.