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

Google语音转文字JSON嵌套字典访问报KeyError: 'confidence'问题咨询

两类API返回结构的核心差异
  • 最终结果标记规则不同:IBM Watson返回的所有results条目均为最终结果,每个alternatives数组元素固定携带confidence字段。Google Cloud Speech to Text 区分中间增量结果和最终结果:results数组中每个条目包含is_final字段,仅is_final = true的最终结果条目,其alternatives[0](置信度最高的转写结果)才会默认携带confidence字段,is_final = false的中间流式结果仅返回transcript字段,无confidence。
  • 可选字段开启规则不同:IBM Watson默认返回所有alternatives条目的confidence,Google侧如果需要获取非top1的alternatives的confidence,或者逐词级别的置信度,必须在发起识别请求时显式开启enable_word_confidence参数为true,否则非首位的alternatives不会返回confidence字段。
  • 字段缺省规则不同:Google侧部分定制模型、短语音识别场景下,即使是最终结果也可能存在confidence字段缺省的情况,IBM侧无该类缺省规则。
修复方案

调整遍历逻辑,先过滤非最终结果,再用get方法读取字段避免KeyError,示例代码如下:

# Google STT confidence 提取逻辑示例
confidence_list = []
for result in data_response["results"]:
    # 跳过非最终的中间结果
    if not result.get("is_final", False):
        continue
    for alt in result["alternatives"]:
        conf = alt.get("confidence")
        # 读取不到confidence时跳过该条目,也可根据需求设置默认值
        if conf is not None:
            confidence_list.append(conf)

# 计算平均置信度
avg_confidence = sum(confidence_list) / len(confidence_list) if confidence_list else 0.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:15:04