【问题标题】:Parsing YAML file to gather certain data解析 YAML 文件以收集某些数据
【发布时间】:2014-12-16 18:44:07
【问题描述】:

我对 .yaml 和 python 完全陌生。我试图弄清楚如何从 yaml 解析数据以收集我需要的某些数据并将其写入不同的文件。

Checking Information:
- Time Stamp: ['2014-10-20 17:10:16', '2014-10-20 17:16:10']
  Unique Number: 60025893
  Accept/Reject: 'Yes'
  Policy ID: '01693'
  Specific name: Axis-447
- Time Stamp: ['2014-10-20 18:10:56', '2014-10-20 18:15:53']
  Unique Number: 15832596
  Accept/Reject: 'No'
  Policy ID: '68975'
  Specific name: Axis-533

上面显示了我的 yaml 文件的一部分。我想尝试提取策略 ID,下面的特定名称和代码显示了我到目前为止所能想到的。

with open("test.yaml", "r") as f: 
    doc = yaml.load(f)
    txt = doc['Checking Information']['Specific name']
    print(txt)

如果有人可以帮助我,将不胜感激。

【问题讨论】:

  • 您如何获得doc?在我看来,您需要阅读 f 的内容,将其传递给 YAML 函数以读取它并将其转换为 doc
  • 哦,我的代码中漏掉了一行。我已经编辑了我的问题。我使用 yaml.load 来获取文档。

标签: python-3.x yaml pyyaml


【解决方案1】:

doc['Checking Information'] 实际上是一个数组。在访问单个键之前,您需要遍历数组。

试试:

txt = doc['Checking Information']
for element in txt:
    print(element['Specific name'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多