經過一番研究,我可以使用Pyyaml將空字符串作爲塊文字(在'|>'中的樣式)轉儲到YAML文件中。我的工作部分基於Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?。
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)
輸出:
foo:
folded: >
literal: |
不過,我不能找到一種方法來轉儲塊樣式列表爲空。爲此,我試圖弄亂yaml/emitter.py並意識到我需要一個非空列表來以塊的形式轉儲它。
無論如何,這項努力並沒有白費,而是相當令人興奮:) 我希望有人會覺得這個有用,或者可能有一些東西可以分享。