抑制YAML输出中的!!python/unicode

4

在Python 2.7中,使用ruamel.yaml或PyYAML将字典data = {'abc': 'def'}转换为YAML格式(default_flow_style=False)时,你会得到以下结果:

abc: def

这很好。但是,如果您将所有字符串都转换为Unicode(通过添加u前缀或使用from __future__ import unicode_literals),则会将其转换为:

!!python/unicode 'abc': !!python/unicode 'def'

如何在不使用safe_dump()的情况下将所有字符串(unicode前缀或非前缀)转储到没有标签的文本中? 添加allow_unicode=True并不能解决问题。

生成不需要的标签的完整示例:

from __future__ import unicode_literals

import sys
import ruamel.yaml

data = {'abc': 'def'}
ruamel.yaml.safe_dump(data, sys.stdout, allow_unicode=True, default_flow_style=False)
1个回答

4
您需要一个不同的表示器来处理将unicode转换为str的过程:
from __future__ import unicode_literals

import sys
import ruamel.yaml

def my_unicode_repr(self, data):
    return self.represent_str(data.encode('utf-8'))

ruamel.yaml.representer.Representer.add_representer(unicode, my_unicode_repr)

data = {'abc': u'def'}
ruamel.yaml.dump(data, sys.stdout, allow_unicode=True, default_flow_style=False)

提供:

abc: def

对于PyYAML来说,同样可以实现这个功能,只需要将ruamel.yaml替换为yaml即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接