首页 > 解决方案 > Google Speech to Text - 无法将输出写入文本文件

问题描述

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

任何建议将不胜感激。

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")```

标签: pythonspeech-to-textgoogle-speech-api

解决方案


看起来 txt 不是字符串。您可以尝试使用 str(txt) 将其转换为字符串。

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


推荐阅读