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

查看:25
本文介绍了在 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 tutorial, "如何在 Python 中解析 YAML 文件",将 Python dict 转换为对象?",但我还没有找到关于如何从解析的 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 text"?

How do I access the text "branch1 text"?

"YAML 解析和 Python?" 提供了解决方案,但我在访问来自更复杂的 YAML 文件的数据.而且,我想知道是否有某种标准方法可以从解析的 YAML 文件中访问数据,可能类似于tree 迭代" 或 "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天全站免登陆