You need to enable JavaScript to run this app. Python如何提取韦氏词典API返回的非固定索引嵌套列表内容
优惠活动
大模型
产品
解决方案
定价
更多

Python如何提取韦氏词典API返回的非固定索引嵌套列表内容

韦氏API嵌套内容提取方案

对于嵌套层级不固定、索引位置随机的结构化数据,最优方案是使用递归遍历所有节点,只匹配固定的字段标识,完全不需要关心层级和索引位置。

完整实现代码

def extract_mw_content(nested_data):
    result = {
        "definitions": [],  # 存储释义文本
        "examples": []      # 存储例句文本
    }

    def recursive_traverse(node):
        # 当前节点为列表时递归遍历每个子元素
        if isinstance(node, list):
            for item in node:
                recursive_traverse(item)
        # 当前节点为字典时匹配目标字段
        elif isinstance(node, dict):
            # 提取dt下的释义内容
            if "dt" in node:
                for dt_item in node["dt"]:
                    if isinstance(dt_item, list) and len(dt_item) >= 2 and dt_item[0] == "text":
                        result["definitions"].append(dt_item[1].strip())
            # 提取vis下的例句内容
            if "vis" in node:
                for vis_item in node["vis"]:
                    if isinstance(vis_item, dict) and "t" in vis_item:
                        result["examples"].append(vis_item["t"].strip())
        # 其他类型节点直接跳过
        else:
            return

    recursive_traverse(nested_data)
    return result


# 测试示例数据
sample_data = [[['sense',
   {'dt': [['text',
            '{bc}known or understood only by a small group of people '
            '{bc}{sx|esoteric||} '],
           ['vis',
            [{'aq': {'auth': 'Gillian Flynn'},
              't': '"Nick, even I don\'t understand those clues," Go said. '
                   '"They\'re all {wi}inside baseball{/wi} between you and Amy '
                   '… "'},
             {'aq': {'auth': 'Deb Amien'},
              't': 'It might be a bit {wi}inside baseball{/wi} to some, but I '
                   'love it when crossword constructors poke fun at '
                   'puzzle-making conventions.'},
             {'aq': {'auth': 'Zach Johnston'},
              't': 'We have, however, tried to shy away from the '
                   "super-scientific words—they're just too {wi}inside "
                   "baseball{/wi} unless you're an actual distiller."},
             {'aq': {'auth': 'Dan McGowan'},
              't': 'This is very {wi}inside baseball{/wi}, but the House Rules '
                   'Committee meets today to consider a series of rule changes '
                   'for the 2021 and 2022 legislative sessions.'},
             {'aq': {'auth': 'Brandon Katz'},
              't': 'Earnings reports are always a bit dry and {wi}inside '
                   'baseball{/wi} for the casual entertainment industry '
                   'observer.'}]]]}]]]

# 调用函数获取结果
output = extract_mw_content(sample_data)
# 打印验证
print("提取到的释义:")
for d in output["definitions"]:
    print(d)
print("\n提取到的例句:")
for e in output["examples"]:
    print(e)

补充说明

  • 整体逻辑不依赖任何固定索引,只要API返回结构保留dt、vis、text、t这类业务字段,就能稳定提取内容,适配不同单词的返回结构
  • 如果需要提取其他内容(比如例句作者信息、同义词),只要在字典判断分支里新增对应字段的匹配逻辑即可
  • 如果需要清理返回内容里的{bc}、{wi}这类标记标签,可以新增正则替换逻辑:
import re
def clean_text(raw_text):
    return re.sub(r'\{[^}]+\}', '', raw_text).strip()

直接调用clean_text()处理提取到的文本即可得到纯内容。

内容的提问来源于stack exchange,提问作者Steve10297

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 21:27:03