Google 语音转文本 - 无法将输出写入文本文件

Google Speech to Text - Can't write output to text file

我正在尝试写入文本文件。它似乎每次都失败了。我可以写 .write("test") 但将 google 转录输出写入文件似乎失败了。

如有任何建议,我们将不胜感激。

import speech_recognition as sr

from os import path

from pprint import pprint

audio_file = path.join(path.dirname(path.realpath(__file__)), "RobertP.wav")

r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
    audio = r.record(source)

try:
    txt = r.recognize_google(audio, show_all=True)
    pprint (txt)

except:
    print("Didn't work.")

try:
    f = open("tester.txt", "w+")
    f.write(txt)
    f.close()
except:
    print("Couldn't write to file")```

看起来 txt 不是字符串。您可以尝试使用 str(txt).

将其转换为字符串

顺便说一句: 出于测试原因,最好删除 try/except 以获得错误。程序运行后,您可以再次添加它,.