pyyaml产生了不希望的!! python / unicode输出

问题描述 投票:25回答:2

我正在使用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

python pyyaml
2个回答
43
投票

我尝试了许多组合,唯一能始终产生正确的YAML输出的组合是:

yaml.safe_dump(data, file(filename,'w'), encoding='utf-8', allow_unicode=True)

0
投票

受接受的答案启发,safe_dump可以产生预期的结果,我检查了python2.7/site-packages/yaml/representer.py的来源,发现Representerdumpsafe_dumpunicode使用了不同的表示函数]。

并且表示功能可以用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。

© www.soinside.com 2019 - 2024. All rights reserved.