python - 如何将 YAML 文件解析/读取到 Python 对象中?

标签 python parsing yaml

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

例如,这个 YAML:

Person:
  name: XYZ

到这个 Python 类:

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

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

顺便说一句,我正在使用 PyYAML。

最佳答案

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

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

你已经像这样安装了 PyYAML:

pip install PyYAML

Python 代码如下所示:

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

变量 dataMap 现在包含一个带有树数据的字典。如果你使用 PrettyPrint 打印 dataMap,你会得到类似的东西:

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

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

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

你有一本字典,现在你必须把它转换成一个 Python 对象:

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

那么你可以使用:

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

并关注“Convert Python dict to object”。

有关更多信息,您可以查看 pyyaml.orgthis .

关于python - 如何将 YAML 文件解析/读取到 Python 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6866600/

相关文章:

python - Emacs 函数向我所在的 python 函数发送消息

python - Odoo 属性错误 : 'module' object has no attribute 'getppid' -- windows os. getppid

java - 我可以可靠地使用 os.version 值来确定 Linux 发行版吗?

Javascript - 解析 XML 文档以创建数组

python - numpy 中向量化函数的性能行为

python - 将两个 UTF-8 字节相互分割的有效方法

python - 如何解析非结构化的表类数据?

Perl YAML::Load 无法加载 YAML::Dump 转储的 YAML

docker - Calicoctl 错误 : "bash:/usr/local/bin/calicoctl: Permission denied ubuntu

css - 杰基尔和萨斯;我可以使用元数据吗?