Python 2.7 抑制!!YAML输出中的python/unicode
当转储(ruamel.yaml,PyYAML)时,dictPython 2.7 抑制!!YAML输出中的python/unicode,python-2.7,yaml,pyyaml,ruamel.yaml,Python 2.7,Yaml,Pyyaml,Ruamel.yaml,当转储(ruamel.yaml,PyYAML)时,dictdata={'abc':'def'} 作为Python 2.7中的YAML(使用default\u flow\u style=False),您将获得: abc: def 这很好。但是,如果将所有字符串设置为unicode(通过u前缀或使用from\uuuuuu\uuuuu导入unicode\u文本),则会转储为: !!python/unicode 'abc': !!python/unicode 'def' 如何在不使用safe\u d
data={'abc':'def'}
作为Python 2.7中的YAML(使用default\u flow\u style=False
),您将获得:
abc: def
这很好。但是,如果将所有字符串设置为unicode(通过u
前缀或使用from\uuuuuu\uuuuu导入unicode\u文本
),则会转储为:
!!python/unicode 'abc': !!python/unicode 'def'
如何在不使用safe\u dump()
的情况下转储所有不带标记的字符串(无论是否带有unicode前缀)?添加allow\u 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)
您需要一个不同的representer来处理
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