Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 抑制!!YAML输出中的python/unicode_Python 2.7_Yaml_Pyyaml_Ruamel.yaml - Fatal编程技术网

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

Python 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

当转储(ruamel.yaml,PyYAML)时,dict
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