首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析嵌套列表

解析嵌套列表
EN

Stack Overflow用户
提问于 2022-04-07 23:07:55
回答 1查看 146关注 0票数 -1

因此,我有一个嵌套列表,需要对其进行解析和操作。我从Merriam Webster字典API获得这些数据。

以下是JSON数据的样子:

代码语言:javascript
复制
[
  {
    "meta": {
      "id": "trellis:2",
      "uuid": "3a22ee1d-f552-4836-bd2a-3e6b2fe11884",
      "sort": "200364400",
      "src": "collegiate",
      "section": "alpha",
      "stems": [
        "trellis",
        "trellised",
        "trellises",
        "trellising"
      ],
      "offensive": false
    },
    "hom": 2,
    "hwi": {
      "hw": "trellis"
    },
    "fl": "verb",
    "ins": [
      {
        "if": "trel*lised"
      },
      {
        "if": "trel*lis*ing"
      },
      {
        "if": "trel*lis*es"
      }
    ],
    "def": [
      {
        "vd": "transitive verb",
        "sseq": [
          [
            [
              "sense",
              {
                "sn": "1",
                "dt": [
                  [
                    "text",
                    "{bc}to provide with a trellis"
                  ]
                ],
                "sdsense": {
                  "sd": "especially",
                  "dt": [
                    [
                      "text",
                      "{bc}to train (a plant, such as a vine) on a trellis"
                    ]
                  ]
                }
              }
            ]
          ],
          [
            [
              "sense",
              {
                "sn": "2",
                "dt": [
                  [
                    "text",
                    "{bc}to cross or interlace on or through {bc}{sx|interweave||}"
                  ]
                ]
              }
            ]
          ]
        ]
      }
    ],
    "date": "15th century{ds||1||}",
    "shortdef": [
      "to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis",
      "to cross or interlace on or through : interweave"
    ]
  },
  {
    "meta": {
      "id": "trellis:1",
      "uuid": "db2e1190-dd93-45f3-831c-9e9536aab601",
      "sort": "200364300",
      "src": "collegiate",
      "section": "alpha",
      "stems": [
        "trellis",
        "trellised",
        "trellises"
      ],
      "offensive": false
    },
    "hom": 1,
    "hwi": {
      "hw": "trel*lis",
      "prs": [
        {
          "mw": "ˈtre-ləs",
          "sound": {
            "audio": "trelli01",
            "ref": "c",
            "stat": "1"
          }
        }
      ]
    },
    "fl": "noun",
    "def": [
      {
        "sseq": [
          [
            [
              "sense",
              {
                "sn": "1",
                "dt": [
                  [
                    "text",
                    "{bc}a frame of latticework used as a screen or as a support for climbing plants"
                  ]
                ]
              }
            ]
          ],
          [
            [
              "sense",
              {
                "sn": "2",
                "dt": [
                  [
                    "text",
                    "{bc}a construction (such as a summerhouse) chiefly of latticework"
                  ]
                ]
              }
            ]
          ],
          [
            [
              "sense",
              {
                "sn": "3",
                "dt": [
                  [
                    "text",
                    "{bc}an arrangement that forms or gives the effect of a lattice "
                  ],
                  [
                    "vis",
                    [
                      {
                        "t": "a {wi}trellis{/wi} of interlacing streams"
                      }
                    ]
                  ]
                ]
              }
            ]
          ]
        ]
      }
    ],
    "uros": [
      {
        "ure": "trel*lised",
        "prs": [
          {
            "mw": "ˈtre-ləst",
            "sound": {
              "audio": "trelli02",
              "ref": "c",
              "stat": "1"
            }
          }
        ],
        "fl": "adjective"
      }
    ],
    "art": {
      "artid": "trellis",
      "capt": "trellis 1"
    },
    "et": [
      [
        "text",
        "Middle English {it}trelis{/it}, from Anglo-French {it}treleis{/it}, from Old French {it}treille{/it} arbor, from Latin {it}trichila{/it} summerhouse"
      ]
    ],
    "date": "14th century{ds||1||}",
    "shortdef": [
      "a frame of latticework used as a screen or as a support for climbing plants",
      "a construction (such as a summerhouse) chiefly of latticework",
      "an arrangement that forms or gives the effect of a lattice"
    ]
  }
]

下面是我想要将数据更改为:我从shortdef中提取定义

代码语言:javascript
复制
Definition (Entry 1/2):
1: to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis

2: to cross or interlace on or through : interweave1: a frame of latticework used as a screen or as a support for climbing plants

Definition (Entry 2/2):
1: a frame of latticework used as a screen or as a support for climbing plants

2: a construction (such as a summerhouse) chiefly of latticework

3: an arrangement that forms or gives the effect of a lattice

下面的代码只能解析非嵌套列表,我很难找到如何修改它以解析嵌套列表:

代码语言:javascript
复制
defin_formatted = ""
word_defin = []
for i in data:
    word_defin.append(i['shortdef'])

for group in word_defin:
    if len(group) > 1:
        result = []
        for i,v in enumerate(group):
            result.append("**{}:** {}".format(i+1, v))
        group = '\n\n'.join(result)
        
    else:
        group = group[0]
    defin_formatted = defin_formatted + group

此代码生成以下输出:

代码语言:javascript
复制
1: to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis

2: to cross or interlace on or through : interweave1: a frame of latticework used as a screen or as a support for climbing plants

2: a construction (such as a summerhouse) chiefly of latticework

3: an arrangement that forms or gives the effect of a lattice

这是非常接近,所以什么是打算,但有缺陷

EN

回答 1

Stack Overflow用户

发布于 2022-04-08 02:46:01

下面是我如何处理这个问题的方法。首先,抽取到一个结构中,它更适合我们想要做的转换,其次,转换/装饰本身。最后一步是构建一个实际的字符串,其中包含所有的定义(或多个定义)。

代码语言:javascript
复制
import warnings
from collections import defaultdict

data2 = defaultdict(dict)
for i, d in enumerate(data):
    try:
        key, num = d['meta']['id'].split(':', 1)
        defs = d['shortdef']
        data2[key][num] = defs
    except KeyError as e:
        warnings.warn(f'caught in data[{i}]: {e!r}')

data2 = {k: [defs for _, defs in sorted(v.items())] for k, v in data2.items()}

在这一点上,我们有一个包含我们想要的信息的结构:

代码语言:javascript
复制
>>> data2
{'trellis': [['a frame of latticework used as a screen or as a support for climbing plants',
   'a construction (such as a summerhouse) chiefly of latticework',
   'an arrangement that forms or gives the effect of a lattice'],
  ['to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis',
   'to cross or interlace on or through : interweave']]}

然后,我们可以进行一些转换(所有的理解),用“(条目i,n)”来修饰定义和示例编号。

代码语言:javascript
复制
nested_lines = [
    (f'Definition of {k} (Entry {i} of {len(v)})',
     [f'{j}: {txt}' for j, txt in enumerate(defs, 1)])
    for k, v in data2.items()
    for i, defs in enumerate(v, 1)
]

我们现在有:

代码语言:javascript
复制
>>> nested_lines
[('Definition of trellis (Entry 1 of 2)',
  ['1: a frame of latticework used as a screen or as a support for climbing plants',
   '2: a construction (such as a summerhouse) chiefly of latticework',
   '3: an arrangement that forms or gives the effect of a lattice']),
 ('Definition of trellis (Entry 2 of 2)',
  ['1: to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis',
   '2: to cross or interlace on or through : interweave'])]

现在,如果我们想打印这些定义,比如说,我们可以:

代码语言:javascript
复制
text = '\n\n'.join(['\n'.join([k, '', '\n'.join(v)]) for k, v in nested_lines])

>>> print(text)
Definition of trellis (Entry 1 of 2)

1: a frame of latticework used as a screen or as a support for climbing plants
2: a construction (such as a summerhouse) chiefly of latticework
3: an arrangement that forms or gives the effect of a lattice

Definition of trellis (Entry 2 of 2)

1: to provide with a trellis; especially : to train (a plant, such as a vine) on a trellis
2: to cross or interlace on or through : interweave
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71789897

复制
相关文章

相似问题

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