如何迫使PYYAML作为Unicode对象加载字符串?
-
04-10-2019 - |
题
PYYAML软件包将未标记的字符串作为Unicode或Str对象加载,具体取决于其内容。
我想在整个程序中使用Unicode对象(不幸的是,现在还不能切换到Python 3)。
是否有一种简单的方法来强迫Pyyaml始终加载Unicode对象?我不想和我的yaml混乱 !!python/unicode
标签。
# Encoding: UTF-8
import yaml
menu= u"""---
- spam
- eggs
- bacon
- crème brûlée
- spam
"""
print yaml.load(menu)
输出: ['spam', 'eggs', 'bacon', u'cr\xe8me br\xfbl\xe9e', 'spam']
我想: [u'spam', u'eggs', u'bacon', u'cr\xe8me br\xfbl\xe9e', u'spam']
解决方案
这是一个版本,通过始终输出来覆盖字符串的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
""")
(以上给出 [u'spam', u'eggs', u'bacon', u'cr\xe8me br\xfbl\xe9e', u'spam']
)
我还没有测试 LibYAML
(基于C的解析器)尽管我无法编译,所以我将留下其他答案。
其他提示
这是您可以用来替换的功能 str
和 unicode
解码输出的类型 PyYAML
:
def make_str_unicode(obj):
t = type(obj)
if t in (list, tuple):
if t == tuple:
# Convert to a list if a tuple to
# allow assigning to when copying
is_tuple = True
obj = list(obj)
else:
# Otherwise just do a quick slice copy
obj = obj[:]
is_tuple = False
# Copy each item recursively
for x in xrange(len(obj)):
obj[x] = make_str_unicode(obj[x])
if is_tuple:
# Convert back into a tuple again
obj = tuple(obj)
elif t == dict:
for k in obj:
if type(k) == str:
# Make dict keys unicode
k = unicode(k)
obj[k] = make_str_unicode(obj[k])
elif t == str:
# Convert strings to unicode objects
obj = unicode(obj)
return obj
print make_str_unicode({'blah': ['the', 'quick', u'brown', 124]})
不隶属于 StackOverflow