【问题标题】:YAML python parserYAML python 解析器
【发布时间】:2016-03-12 16:25:09
【问题描述】:

我有一个如下格式的 YAML 文件:

innings:
      - 1st innings:
          team: England
          deliveries:
            - 0.1:
                batsman: ME Trescothick
                bowler: Shoaib Akhtar
                extras:
                  wides: 1
                non_striker: AJ Strauss
                runs:
                  batsman: 0
                  extras: 1
                  total: 1
            - 0.2:
                batsman: ME Trescothick
                bowler: Shoaib Akhtar
                non_striker: AJ Strauss
                runs:
                  batsman: 0
                  extras: 0
                  total: 0
      - 2nd innings:
          team: Pakistan
          deliveries:
            - 0.1:
                batsman: Shoaib Malik
                bowler: D Gough
                non_striker: Mohammad Hafeez
                runs:
                  batsman: 2
                  extras: 0
                  total: 2
            - 0.2:
                batsman: Shoaib Malik
                bowler: D Gough
                extras:
                  wides: 5
                non_striker: Mohammad Hafeez
                runs:
                  batsman: 0
                  extras: 5
                  total: 5

我正在使用以下代码访问 yaml 数据:

with open(fpath, 'r') as stream:
    datamap = yaml.safe_load(stream)
x = bunchify(datamap)
print x.innings[0]

打印语句给我以下结果:

- 1st innings:
          team: England
          deliveries:
            - 0.1:
                batsman: ME Trescothick
                bowler: Shoaib Akhtar
                extras:
                  wides: 1
                non_striker: AJ Strauss
                runs:
                  batsman: 0
                  extras: 1
                  total: 1
            - 0.2:
                batsman: ME Trescothick
                bowler: Shoaib Akhtar
                non_striker: AJ Strauss
                runs:
                  batsman: 0
                  extras: 0
                  total: 0

但是当我尝试使用以下语句访问第一局时:

print x.innings[0].1st innings

它会抛出一个错误。我什至尝试将字符串“1st innings”分配给一个变量并使用它。但是它会抛出一个错误:

inn = "1st innings"
print x.innings[0].inn

我需要获得总运行次数。为此,我需要添加列表中每个球的总数[0.1, 0.2,...]

【问题讨论】:

  • 你不能这样做 x.innings[0].1st innings... 它在空间中断,所以你正在做 x.innings[0].1st 这也是不正确的。也许你的意思是x.innings[0]['1st innings']
  • 1. 1st innings 不是有效的 identifier name。 2. x.innings[0].inn 正在寻找一个字面上命名为inn 的属性,它不关心你分配给变量inn 的内容。您需要getattr 或关键符号,如@cricket_007 所示。
  • @cricket_007 成功了。但是,当我尝试使用 print x.innings[0]['1st innings'].deliveries[2].runs 访问每个球的总数时,它会引发错误。我在这里犯了什么错误。你能告诉我计算每局总得分的方法吗?
  • 你需要停止使用点符号,就像你有一个对象一样。继续使用关键符号。
  • >>> x['innings'][0]['1st innings']['deliveries'][0][0.1]['runs'] 返回{'batsman': 0, 'extras': 1, 'total': 1} 字典键可以是任何可散列的对象,甚至是浮点数或整数,因此您希望使用0.1 数字而不是字符串。

标签: python dictionary yaml


【解决方案1】:

Converting to Python lists & dictionaries,你得到了这个结构,称之为x

来自 cmets 的一些值是

  • x.inningsx['innings'] - 返回由 "1st innings""2nd innings" 键入的 Python 字典列表
  • x.innings[0] - 从上面的列表中返回第一个字典
  • x.innings[0]['1st innings'] - 返回innings 列表中第一项中"1st innings" 键的字典值。
  • x.innings[0]['1st innings']['deliveries'] - 返回由 0.10.2 键入的 Python 字典列表。
  • x.innings[0]['1st innings']['deliveries'][0] - 从上面的列表中返回第一个字典
  • x.innings[0]['1st innings']['deliveries'][0][0.1] - 返回deliveries 列表中第一项中0.1 键的JSON 对象值。
  • x.innings[0]['1st innings']['deliveries'][0][0.1]['runs'] - 返回'runs' 的字典

数据:

{
  "innings": [
    {
      "1st innings": {
        "deliveries": [
          {
            0.1: {
              "batsman": "ME Trescothick", 
              "bowler": "Shoaib Akhtar", 
              "runs": {
                "batsman": 0, 
                "total": 1, 
                "extras": 1
              }, 
              "extras": {
                "wides": 1
              }, 
              "non_striker": "AJ Strauss"
            }
          }, 
          {
            0.2: {
              "batsman": "ME Trescothick", 
              "bowler": "Shoaib Akhtar", 
              "runs": {
                "batsman": 0, 
                "total": 0, 
                "extras": 0
              }, 
              "non_striker": "AJ Strauss"
            }
          }
        ], 
        "team": "England"
      }
    }, 
    {
      "2nd innings": { ... }
    }
  ]
}

【讨论】:

  • 我使用了“转换为 JSON”文本链接中的工具
  • 当您使用 yaml.load 加载 YAML 字符串时,它会返回一个对应于 YAML 对象的 python 对象,因此在本例中是字典和列表。
  • @MarkMikofski 当然可以,但是 JSON 语法或多或少直接等同于 Python 列表和字典
  • 真,除了键。根据JSON.org ECMA standard,JSON 键必须是字符串,因此 json.dumps(x) (其中 x 是加载的 YAML 字符串)将浮动键转换为字符串。 =_o_/=
  • @MarkMikofski 所有的优点。已编辑答案以反映 Python 对象
【解决方案2】:

@laxmi23 欢迎来到 Stack Overflow。请阅读How to ask a good question 上的部分以提出获得更多答案和更多投票的问题。您可能还喜欢阅读How to create a mimimal, complete and verifiable example

您的问题可能被否决了,因为它看来您在发布之前可能没有进行足够的研究。特别是 YAML Tutorial on load 的部分说它返回一个 Python 对象。搜索Python Tutorial on Data Types,您可以看到如何索引各种Python 对象,例如ListsDictionaries,这正是您需要的:

>>> import yaml  # use the PyYAML package to load your YAML string
>>> yaml.load("""
innings:
- 1st innings:
    deliveries:
    - 0.1:
        batsman: ME Trescothick
        bowler: Shoaib Akhtar
        extras: {wides: 1}
        non_striker: AJ Strauss
        runs: {batsman: 0, extras: 1, total: 1}
    - 0.2:
        batsman: ME Trescothick
        bowler: Shoaib Akhtar
        non_striker: AJ Strauss
        runs: {batsman: 0, extras: 0, total: 0}
    team: England
- 2nd innings:
    deliveries:
    - 0.1:
        batsman: Shoaib Malik
        bowler: D Gough
        non_striker: Mohammad Hafeez
        runs: {batsman: 2, extras: 0, total: 2}
    - 0.2:
        batsman: Shoaib Malik
        bowler: D Gough
        extras: {wides: 5}
        non_striker: Mohammad Hafeez
        runs: {batsman: 0, extras: 5, total: 5}
    team: Pakistan
""")

{'innings': [{'1st innings': {'deliveries': [{0.1: {'batsman': 'ME Trescothick',
       'bowler': 'Shoaib Akhtar',
       'extras': {'wides': 1},
       'non_striker': 'AJ Strauss',
       'runs': {'batsman': 0, 'extras': 1, 'total': 1}}},
     {0.2: {'batsman': 'ME Trescothick',
       'bowler': 'Shoaib Akhtar',
       'non_striker': 'AJ Strauss',
       'runs': {'batsman': 0, 'extras': 0, 'total': 0}}}],
    'team': 'England'}},
  {'2nd innings': {'deliveries': [{0.1: {'batsman': 'Shoaib Malik',
       'bowler': 'D Gough',
       'non_striker': 'Mohammad Hafeez',
       'runs': {'batsman': 2, 'extras': 0, 'total': 2}}},
     {0.2: {'batsman': 'Shoaib Malik',
       'bowler': 'D Gough',
       'extras': {'wides': 5},
       'non_striker': 'Mohammad Hafeez',
       'runs': {'batsman': 0, 'extras': 5, 'total': 5}}}],
    'team': 'Pakistan'}}]}

查看响应{'innings': [{'1st innings': ... 的第一行可以看到外部对象是一个字典,其中包含一个字典列表。因此,使用括号访问 Python 对象,如 Python 数据类型教程所示。

>>> y['innings'][0]['1st innings']  # index into the returned Python object

{'deliveries': [{0.1: {'batsman': 'ME Trescothick',
    'bowler': 'Shoaib Akhtar',
    'extras': {'wides': 1},
    'non_striker': 'AJ Strauss',
    'runs': {'batsman': 0, 'extras': 1, 'total': 1}}},
  {0.2: {'batsman': 'ME Trescothick',
    'bowler': 'Shoaib Akhtar',
    'non_striker': 'AJ Strauss',
    'runs': {'batsman': 0, 'extras': 0, 'total': 0}}}],
 'team': 'England'}

正如我在上面的评论中所说,Python 字典键可以是任何可散列的,甚至是浮点数。所以为了找到runs 使用0.1 作为数字而不是字符串。假设我们将load 响应捕获为x

>>> x['innings'][0]['1st innings']['deliveries'][0][0.1]['runs']
{'batsman': 0, 'extras': 1, 'total': 1}

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 2019-06-27
    • 2012-01-11
    • 2010-11-11
    • 2018-09-02
    • 2018-02-16
    • 1970-01-01
    • 2010-09-22
    • 2011-05-19
    相关资源
    最近更新 更多