编程语言
首页 > 编程语言> > Python字典使用PyYaml进入yaml文档

Python字典使用PyYaml进入yaml文档

作者:互联网

我有两个python词典,我想写一个yaml文件,有两个文件:

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}

yaml文件应如下所示:

--- !define
one: 1
two: 2
three: 3

-- !action
run: yes
print: no
report: maybe
...

使用PyYaml我没有找到明确的方法来做到这一点.我确信有一个简单的方法,但深入研究PyYaml文档,只会让我感到困惑.我需要自卸车,发射器还是什么?这些类型产生什么类型的输出? Yaml文字? yaml节点? YAMLObject?无论如何,如果有任何澄清,我将不胜感激.

按照下面unutbu的回答,这是我能提出的最简洁的版本:

DeriveYAMLObjectWithTag是一个创建新类的函数,该类派生自具有所需标记的YAMLObject:

def DeriveYAMLObjectWithTag(tag):
    def init_DeriveYAMLObjectWithTag(self, **kwargs):
        """ __init__ for the new class """
        self.__dict__.update(kwargs)

    new_class = type('YAMLObjectWithTag_'+tag,
                    (yaml.YAMLObject,),
                    {'yaml_tag' : '!{n}'.format(n = tag),
                    '__init__' :  init_DeriveYAMLObjectWithTag})
    return new_class

以下是如何使用DeriveYAMLObjectWithTag获取所需的Yaml:

definitions = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
namespace = [DeriveYAMLObjectWithTag('define')(**definitions),
             DeriveYAMLObjectWithTag('action')(**actions)]

text = yaml.dump_all(namespace,
                     default_flow_style = False,
                     explicit_start = True)

感谢所有回答的人.我似乎PyYaml缺乏功能,这是克服它的最优雅的方法.

解决方法:

怎么样:

class Bunch(yaml.YAMLObject):
    yaml_tag = u'!Bunch'
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        return '{c}({a})'.format(
            c = self.__class__.__name__,
            a = ', '.join(
                ['='.join(map(str,item)) for item in self.__dict__.items()]))
tag_names = ['define', 'action']
namespace = {}
for name in tag_names:
    namespace[name] = type(name, (Bunch,), {'yaml_tag':u'!{n}'.format(n = name)})

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
text = yaml.dump_all([namespace['define'](**definitions),
                      namespace['action'](**actions)],
                     default_flow_style = False,
                     explicit_start = True)
print(text)

产量

--- !define
one: 1
three: 3
two: 2
--- !action
print: 'no'
report: maybe
run: 'yes'

并将YAML加载回Python对象:

for item in  yaml.load_all(text):
    print(item)
    # define(one=1, three=3, two=2)
    # action(print=no, report=maybe, run=yes)

YAMLObject的子类用于创建application-specific tags.

标签:pyyaml,python,yaml
来源: https://codeday.me/bug/20190725/1536161.html