【问题标题】:pyyaml is producing undesired !!python/unicode outputpyyaml 正在产生不希望的 !!python/unicode 输出
【发布时间】:2013-12-19 14:34:17
【问题描述】:

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


【解决方案1】:

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

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

【讨论】:

  • 这似乎只是生成!!python/str标签而不是!!python/unicode标签。
  • 稍微适应了 Python 3.6,它工作得很好:yaml.safe_dump({"key" : "foo?"}, open("test3.out",'w'), allow_unicode=True) 编码似乎没有必要,可能是因为 Python3 中的默认文本文件编码,但没有allow_unicode 你会得到@987654326 @在文件中。 `
【解决方案2】:

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

并且表示函数可以用add_representer 覆盖。所以你可以从SafeRepresenter获取represent函数,然后注册到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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2012-02-05
    • 2011-11-02
    • 1970-01-01
    相关资源
    最近更新 更多