在Python中解析YAML文件并访问数据? [英] Parsing a YAML file in Python, and accessing the data?

查看:230
本文介绍了在Python中解析YAML文件并访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是YAML的新手,一直在寻找解析YAML文件和使用/访问已解析YAML数据的方法.

I am new to YAML and have been searching for ways to parse a YAML file and use/access the data from the parsed YAML.

我遇到了有关如何解析YAML文件的说明,例如PyYAML 教程,"如何在Python中解析YAML文件", "将Python字典转换为对象吗?",但我还没有发现关于如何从已解析的YAML文件访问数据的简单示例.

I have come across explanations on how to parse the YAML file, for example, the PyYAML tutorial, "How can I parse a YAML file in Python", "Convert Python dict to object?", but what I haven't found is a simple example on how to access the data from the parsed YAML file.

假设我有一个YAML文件,例如:

Assume I have a YAML file such as:

 treeroot:
     branch1: branch1 text
     branch2: branch2 text

如何访问文本"branch1文本"?

How do I access the text "branch1 text"?

" YAML解析和Python?"提供了解决方案,但是我在访问来自更复杂的YAML文件的数据.并且,我想知道是否存在某种标准方法来从已解析的YAML文件访问数据,可能类似于" elementpath "表示法或可能是解析XML文件时使用的是什么?

"YAML parsing and Python?" provides a solution, but I had problems accessing the data from a more complex YAML file. And, I'm wondering if there is some standard way of accessing the data from a parsed YAML file, possibly something similar to "tree iteration" or "elementpath" notation or something which would be used when parsing an XML file?

推荐答案

由于PyYAML的yaml.load()函数将YAML文档解析为本地Python数据结构,因此您只能按键或索引访问项目.使用您所链接问题的示例:

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

要访问branch1 text,请使用:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

因为在您的YAML文档中,branch1项的值在treeroot项下.

because, in your YAML document, the value of the branch1 key is under the treeroot key.

这篇关于在Python中解析YAML文件并访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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