代码之家  ›  专栏  ›  技术社区  ›  ï¾ ï¾ ï¾

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

  •  26
  • ï¾ ï¾ ï¾  · 技术社区  · 15 年前

    PyYAML包根据未标记字符串的内容将其加载为unicode或str对象。

    有没有一种简单的方法来强制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']

    2 回复  |  直到 15 年前
        1
  •  27
  •   cryo    15 年前

    下面是一个版本,它通过总是输出 unicode . 实际上,这可能是我发布的其他响应的相同结果,除了shorter(即,您仍然需要确保将自定义类中的字符串转换为 还是通过了 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

        2
  •  3
  •   cryo    15 年前

    这里有一个函数可以用来替换 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]})