如何强制PyYAML将字符串作为unicode对象加载?

Pet*_*rin 30 python python-2.x pyyaml

PyYAML包将未标记的字符串作为unicode或str对象加载,具体取决于它们的内容.

我想在整个程序中使用unicode对象(不幸的是,还不能切换到Python 3).

是否有一种简单的方法可以强制PyYAML始终对字符串加载unicode对象?我不想用!!python/unicode标签弄乱我的YAML .

# Encoding: UTF-8

import yaml

menu= u"""---
- spam
- eggs
- bacon
- crème brûlée
- spam
"""

print yaml.load(menu)
Run Code Online (Sandbox Code Playgroud)

输出: ['spam', 'eggs', 'bacon', u'cr\xe8me br\xfbl\xe9e', 'spam']

我想要: [u'spam', u'eggs', u'bacon', u'cr\xe8me br\xfbl\xe9e', u'spam']

cry*_*ryo 25

这是一个通过始终输出覆盖PyYAML处理字符串的版本unicode.实际上,这可能是我发布的其他响应的相同结果,除了更短(即您仍然需要确保自定义类中的字符串转换为unicode或传递unicode如果使用自定义处理程序字符串自己字符串):

# -*- coding: utf-8 -*-
import yaml
from yaml import Loader, SafeLoader

def construct_yaml_str(self, node):
    # Override the default string handling function 
    # to always return unicode objects
    return self.construct_scalar(node)
Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)

print yaml.load(u"""---
- spam
- eggs
- bacon
- crème brûlée
- spam
""")
Run Code Online (Sandbox Code Playgroud)

(以上给出 [u'spam', u'eggs', u'bacon', u'cr\xe8me br\xfbl\xe9e', u'spam'])

我没有测试它LibYAML(基于c的解析器),因为我无法编译它,所以我会留下另一个答案.

  • 这个答案被接受已经两年多了,pyYAML仍然会返回`str`对象.现在可能有一种更简单的方法来强制所有unicode输出吗?我想要一个更新的答案. (3认同)