You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套字典结构中提取duration字段对应的时间文本值

错误原因

你的取值路径层级错误,duration 并不在字典的根层级下,直接访问根字典的duration键找不到对应值,才触发了列表索引不能为字符串的类型错误。

正确实现方案

你的txt文件每行是一个独立的Python字典结构,使用ast.literal_eval可以直接把单引号的字典字符串转为Python可操作的字典对象,不需要额外做引号替换。

完整代码

import ast

# 替换为你自己的txt文件路径
file_path = "result.txt"
duration_res = []

with open(file_path, 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        # 跳过文件中的空行
        if not line:
            continue
        data = ast.literal_eval(line)
        # 按正确层级提取时间文本
        dur = data['rows'][0]['elements'][0]['duration']['text']
        duration_res.append(dur)

# 逐行打印所有提取到的时间
print(*duration_res, sep="\n")

取值逻辑说明

按照你给出的字典结构,正确的取值层级为:

  • 根字典下的rows是列表,取第0个元素
  • 该元素下的elements是列表,取第0个元素
  • 该元素下的duration是字典,取其text属性即可得到你需要的时间信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:36:03