You need to enable JavaScript to run this app. Python循环遍历JSON文件打印提取transcript时出现TypeError错误咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python循环遍历JSON文件打印提取transcript时出现TypeError错误咨询

错误触发根因
  • 代码取值逻辑与JSON实际结构不匹配:你给出的JSON结构里,alternatives字段的数据类型是列表(数组),不是可以直接用字符串键访问的字典。
  • 每一个results数组下的元素,其alternatives字段对应的值是包含转写候选的列表,哪怕列表里只有1个转写项,也不能直接用['transcript']的方式从列表取值。列表仅支持整数索引、切片操作,传入字符串作为索引就会触发TypeError: list indices must be integers or slices, not str。
可运行的修正代码

根据“打印所有transcript纯文本”的目标,调整取值逻辑:访问到alternatives字段后,先取出列表内的元素,再读取对应的transcript字段内容。

仅输出最高置信度的转写内容(Google语音识别返回的有效转写默认在alternatives列表的第0位)

import json
filename = "1transcript.json"

with open(filename, "r") as data_file:
    data = json.load(data_file)

for segment in data['results']:
    transcript = segment['alternatives'][0]['transcript']
    print(transcript)

输出所有备选转写内容

如果后续需要拿到每一段下的所有转写候选,可以嵌套一层循环遍历alternatives列表:

import json
filename = "1transcript.json"

with open(filename, "r") as data_file:
    data = json.load(data_file)

for segment in data['results']:
    for candidate in segment['alternatives']:
        print(candidate['transcript'])

内容的提问来源于stack exchange,提问作者Piotr Szymański

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 13:15:04