来自 Google 语音 API 的转录结果的 AttributeError

AttributeError on transcript results from Google Speech API

  1. OS类型和版本:Windows 10, build 16199.1000

  2. Python版本和虚拟环境信息python --versionPython 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32

  3. google-云-python版本:google-cloud-speech==0.27.0

堆栈跟踪:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python27\Lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\Lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "E:/Programming/Python/untitled1/main.py", line 109, in get_transcript
    print('. '.join(resp.alternative.transcript for resp in res), file=sys.stderr)
  File "E:/Programming/Python/untitled1/main.py", line 109, in <genexpr>
    print('. '.join(resp.alternative.transcript for resp in res), file=sys.stderr)
AttributeError: 'SpeechRecognitionResult' object has no attribute 'alternative'

重现步骤:

当我使用这个时:

alternatives = operation.result().results[0].alternatives
    for alternative in alternatives:
        print('Transcript: {}'.format(alternative.transcript))
        print('Confidence: {}'.format(alternative.confidence))

它按预期工作,但只打印第一个抄本。当我使用这个时:

res = operation.result().results
print(res, file=sys.stderr)
print('. '.join(resp.alternative.transcript for resp in res), file=sys.stderr)

我得到上面的异常。我也试过print('. '.join(resp.transcript for resp in res), file=sys.stderr)print('. '.join(resp.alternative for resp in res), file=sys.stderr),就像打印调试一样。两者都在任一属性上抛出 AttributeError

完整的工作示例:https://gist.github.com/mxplusb/8f487a6ff3c781689799bb7ce1dec3f3。 它使用 ffmpeg 以正确的格式从视频文件中删除音频,将其上传到 GCS,然后执行异步语音到文本识别。我正在尝试将所有成绩单连接成一个大文本字符串。

我认为您有一个轻微的错字,因为根据 official documentation 字段是 alternatives 而不是 alternative

alternatives 属性是一个包含 SpeechRecognitionAlternative 个对象的数组,每个对象都有自己的 transcript,在您的示例中,您正在遍历结果,而不是遍历每个备选方案;相反,您假设只有一种选择,我认为这就是为什么您选择输入 alternative 而不是 alternatives 并在整个过程中正确迭代的原因。

要解决此问题,只需将您的 resp.alternative 更改为 resp.alternatives 并正确遍历每个备选方案并打印出其成绩单。