代码之家  ›  专栏  ›  技术社区  ›  Paul Tarjan

Pyyaml:无标签倾倒

  •  66
  • Paul Tarjan  · 技术社区  · 16 年前

    我有

    >>> import yaml
    >>> yaml.dump(u'abc')
    "!!python/unicode 'abc'\n"
    

    但我想要

    >>> import yaml
    >>> yaml.dump(u'abc', magic='something')
    'abc\n'
    

    什么魔法参数强制不加标签?

    5 回复  |  直到 9 年前
        1
  •  83
  •   interjay    16 年前

    你可以使用 safe_dump 而不是 dump .请记住,那时它将无法表示任意的Python对象。还有,当你 load 山药,你会得到 str 对象而不是 unicode .

        2
  •  18
  •   Michał Marczyk    16 年前

    这个怎么样:

    def unicode_representer(dumper, uni):
        node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni)
        return node
    
    yaml.add_representer(unicode, unicode_representer)
    

    这似乎使转储unicode对象的工作方式与为我转储str对象(python 2.6)相同。

    In [72]: yaml.dump(u'abc')
    Out[72]: 'abc\n...\n'
    
    In [73]: yaml.dump('abc')
    Out[73]: 'abc\n...\n'
    
    In [75]: yaml.dump(['abc'])
    Out[75]: '[abc]\n'
    
    In [76]: yaml.dump([u'abc'])
    Out[76]: '[abc]\n'
    
        3
  •  4
  •   Chris Dukes    12 年前

    您需要一个新的dumper类来完成标准dumper类所做的一切,但会覆盖str和unicode的表示器。

    from yaml.dumper import Dumper
    from yaml.representer import SafeRepresenter
    
    class KludgeDumper(Dumper):
       pass
    
    KludgeDumper.add_representer(str,
           SafeRepresenter.represent_str)
    
    KludgeDumper.add_representer(unicode,
            SafeRepresenter.represent_unicode)
    

    这导致

    >>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper)
    [abc, "abc\xE7"]
    
    >>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper,encoding=None)
    [abc, "abc\xE7"]
    

    当然,我仍然在为如何保持这个美丽而苦恼。

    >>> print u'abc\xe7'
    abcç
    

    它会打断后面的yaml.load()。

    >>> yy=yaml.load(yaml.dump(['abc','abc\xe7'],Dumper=KludgeDumper,encoding=None))
    >>> yy
    ['abc', 'abc\xe7']
    >>> print yy[1]
    abc�
    >>> print u'abc\xe7'
    abcç
    
        4
  •  2
  •   JL Peyret    9 年前

    除了Interjay出色的回答之外,如果您处理好文件编码,您可以在重新加载时保持Unicode。

    # -*- coding: utf-8 -*-
    import yaml
    import codecs
    
    data = dict(key = u"abcç\U0001F511")
    
    fn = "test2.yaml"
    with codecs.open(fn, "w", encoding="utf-8") as fo:
        yaml.safe_dump(data, fo)
    
    with codecs.open(fn, encoding="utf-8") as fi:
        data2 = yaml.safe_load(fi)
    
    print ("data2:", data2, "type(data.key):", type(data2.get("key")) )
    
    print data2.get("key")
    

    测试2.yaml 我的编辑器中的内容:

    {key: "abc\xE7\uD83D\uDD11"}

    打印输出:

    ('data2:', {'key': u'abc\xe7\U0001f511'}, 'type(data.key):', <type 'unicode'>) abcç🔑

    另外,读完后 http://nedbatchelder.com/blog/201302/war_is_peace.html 我很确定安全装载/安全卸载是我想要的地方。

        5
  •  0
  •   nowox    10 年前

    我刚开始使用python和yaml,但这可能也有帮助。只需比较输出:

    def test_dump(self):
        print yaml.dump([{'name': 'value'}, {'name2': 1}], explicit_start=True)
        print yaml.dump_all([{'name': 'value'}, {'name2': 1}])
    
    推荐文章