在 Pyyaml 中,如何以块样式表示空字符串和列表?

2023-12-20

我添加了折叠字符串的代表,文字字符串,如中提到的Python 中是否有支持将长字符串转储为块文字或折叠块的 yaml 库? https://stackoverflow.com/questions/6432605/any-yaml-libraries-in-python-that-support-dumping-of-long-strings-as-block-liter。我还添加了表示器,以在转储的 yaml 内容中以块样式打印列表。

但问题是,当字符串为空(即“”)或列表为空时,它们会以非块样式出现在转储的 YAML 内容中。

如何强制 pyyaml 转储程序输出带有“>”或“|”的“”空字符串生成的 YAML 内容中块样式中的 flow_style=False 的样式和空列表?


经过一番研究后,我能够使用 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 并意识到我需要一个非空列表来将其转储为块样式。

不管怎样,这个努力没有白费,反而很令人兴奋:) 我希望有人会觉得这很有用或者有一些东西可以分享。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Pyyaml 中,如何以块样式表示空字符串和列表? 的相关文章

随机推荐