如何将 YAML 文件解析/读入 Python 对象? [英] How to parse/read a YAML file into a Python object?

查看:28
本文介绍了如何将 YAML 文件解析/读入 Python 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 YAML 文件解析/读取为 Python 对象?

例如,这个 YAML:

人员:名称: XYZ

到这个 Python 类:

class Person(yaml.YAMLObject):yaml_tag = '人'def __init__(self, name):self.name = 姓名

顺便说一下,我正在使用 PyYAML.

解决方案

如果您的 YAML 文件如下所示:

#树格式树根:分支 1:名称:节点1分支 1-1:名称:节点 1-1分支 2:名称:节点2分支 2-1:名称:节点 2-1

并且您已经像这样安装了 PyYAML:

pip install PyYAML

Python 代码如下所示:

导入yaml使用 open('tree.yaml') 作为 f:# 使用 safe_load 代替加载dataMap = yaml.safe_load(f)

变量 dataMap 现在包含一个包含树数据的字典.如果您使用 PrettyPrint 打印 dataMap,您将得到如下结果:

<代码>{'树根':{'分支1':{'分支 1-1':{'name': '节点 1-1'},'name': '节点 1'},'分支2':{'分支2-1':{'name': '节点 2-1'},'name': '节点 2'}}}

所以,现在我们已经了解了如何将数据导入到我们的 Python 程序中.保存数据同样简单:

with open('newtree.yaml', "w") as f:yaml.dump(dataMap, f)

您有一个字典,现在您必须将其转换为 Python 对象:

类结构:def __init__(self, **entries):self.__dict__.update(条目)

然后你可以使用:

<预><代码>>>>args = 你的 YAML 字典>>>s = 结构(**参数)>>>秒<__main__.Struct 实例在 0x01D6A738>>>>……

并遵循将 Python dict 转换为对象".

有关更多信息,您可以查看 pyyaml.org这个.

How to parse/read a YAML file into a Python object?

For example, this YAML:

Person:
  name: XYZ

To this Python class:

class Person(yaml.YAMLObject):
  yaml_tag = 'Person'

  def __init__(self, name):
    self.name = name

I am using PyYAML by the way.

解决方案

If your YAML file looks like this:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at pyyaml.org and this.

这篇关于如何将 YAML 文件解析/读入 Python 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆