我正在尝试写入文本文件。似乎每次都失败。我可以编写.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")```
答案 0 :(得分:0)
看起来txt不是字符串。您可以尝试使用str(txt)将其转换为字符串。
顺便说一句: 出于测试原因,最好删除try / except以获得错误。程序运行后,您可以再次添加它。