首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将YAML文件解析/读取为Python对象?

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

Stack Overflow用户
提问于 2011-07-29 06:36:02
回答 3查看 191.7K关注 0票数 113

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

例如,此YAML:

代码语言:javascript
复制
Person:
  name: XYZ

添加到这个Python类:

代码语言:javascript
复制
class Person(yaml.YAMLObject):
  yaml_tag = 'Person'

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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-29 06:49:07

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

代码语言:javascript
复制
# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

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

代码语言:javascript
复制
pip install PyYAML

Python代码如下所示:

代码语言:javascript
复制
import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

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

代码语言:javascript
复制
{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

现在,我们已经了解了如何将数据放入Python程序中。保存数据也很简单:

代码语言:javascript
复制
with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

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

代码语言:javascript
复制
class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

然后,您可以使用:

代码语言:javascript
复制
>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

然后跟着"Convert Python dict to object“。

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

票数 203
EN

Stack Overflow用户

发布于 2016-02-07 23:32:12

来自http://pyyaml.org/wiki/PyYAMLDocumentation

add_path_resolver(tag, path, kind)增加了一个基于路径的隐式标签解析器。路径是形成到表示图中节点的路径的键的列表。路径元素可以是字符串值、整数或无。节点类型可以是字符串、列表、字典或无。

代码语言:javascript
复制
#!/usr/bin/env python
import yaml

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

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

yaml.add_path_resolver('!person', ['Person'], dict)

data = yaml.load("""
Person:
  name: XYZ
""")

print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}

print data['Person'].name
# XYZ
票数 13
EN

Stack Overflow用户

发布于 2017-09-19 04:06:37

下面是一种方法,可以测试用户在virtualenv (或系统)上选择了哪个YAML实现,然后适当地定义load_yaml_file

代码语言:javascript
复制
load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6866600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档