我正在使用pyyaml将对象转储到文件中。对象中有几个unicode字符串。我之前已经做过,但是现在它正在产生如下输出项:
'item': !!python/unicode "some string"
而不是期望的:
'item': 'some string'
我打算将其输出为utf-8。我当前使用的命令是:
yaml.dump(data,file(suite_out,'w'),encoding='utf-8',indent=4,allow_unicode=True)
[在其他位置,我执行以下操作并且有效:
codecs.open(suite_out,"w","utf-8").write(
yaml.dump(suite,indent=4,width=10000)
)
我在做什么错?
Python 2.7.3
我尝试了许多组合,唯一能始终产生正确的YAML输出的组合是:
yaml.safe_dump(data, file(filename,'w'), encoding='utf-8', allow_unicode=True)
受接受的答案启发,safe_dump
可以产生预期的结果,我检查了python2.7/site-packages/yaml/representer.py
的来源,发现Representer
和dump
的safe_dump
对unicode
使用了不同的表示函数]。
并且表示功能可以用add_representer
覆盖。因此,您只需从SafeRepresenter
中获取代表函数,然后将其注册以在dump
中使用即可。
我必须这样做,因为我有一些自定义类型,所以我不能使用safe_dump
。
代码如下:
def represent_unicode(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data)
yaml.add_representer(unicode, represent_unicode)
我的产生输出的命令:
yaml.dump(yml, encoding='utf-8', allow_unicode=True, default_flow_style=False, explicit_start=True)
python版本是2.7.5,PyYMAL是3.10。