Pyyamlにユニコードオブジェクトとして文字列をロードするように強制する方法は?

StackOverflow https://stackoverflow.com/questions/2890146

  •  04-10-2019
  •  | 
  •  

質問

Pyyamlパッケージは、コンテンツに応じて、マークのない文字列をUnicodeまたはSTRオブジェクトとしてロードします。

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

Pyyamlに常にUnicodeオブジェクトをロードするように強制する簡単な方法はありますか?ヤムルと乱雑にしたくありません !!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ベースのパーサー)私はそれをコンパイルできなかったので、他の答えをそのまま残します。

他のヒント

これが交換に使用できる関数です strunicode のデコードされた出力からのタイプ 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]})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top