32

PyYAML パッケージは、マークされていない文字列を、その内容に応じて unicode または str オブジェクトとして読み込みます。

プログラム全体で Unicode オブジェクトを使用したいと考えています (残念ながら、まだ Python 3 に切り替えることはできません)。

PyYAML に常に文字列が Unicode オブジェクトをロードするよう強制する簡単な方法はありますか? !!python/unicodeYAML をタグで乱雑にしたくありません。

# 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']

4

2 に答える 2

27

これは、常に出力することにより、文字列の 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ベースのパーサー)でテストしていません。そのため、他の回答はそのままにしておきます。

于 2010-06-03T15:35:50.903 に答える
3

のデコードされた出力からの型strに置き換えるために使用できる関数を次に示します。unicodePyYAML

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]})
于 2010-06-03T03:49:07.940 に答える