经过一番研究后,我能够使用 Pyyaml 将空字符串转储为 YAML 文件中的块文字(样式为“|>”)。我的工作部分基于Python 中是否有支持将长字符串转储为块文字或折叠块的 yaml 库? https://stackoverflow.com/questions/6432605/any-yaml-libraries-in-python-that-support-dumping-of-long-strings-as-block-liter.
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)
Output:
foo:
folded: >
literal: |
但是,我无法找到以块样式转储空列表的方法。为此,我尝试弄乱 yaml/emitter.py 并意识到我需要一个非空列表来将其转储为块样式。
不管怎样,这个努力没有白费,反而很令人兴奋:)
我希望有人会觉得这很有用或者有一些东西可以分享。