我正在尝试使用 .wav 格式的音频通过语音识别生成文本文件。这是为了获取字幕。我已经得到了文本文件,但现在的问题是文本是在 longgggg 行中生成的。
我希望它们逐行排列(也许 5 个单词后它会转到下一行),因为我想在 tkinter 窗口中显示字幕。正如我所说,我已经让它们显示在 tkinter 窗口上,唯一的问题是文本文件不是逐行生成的。请帮助我。这是我最后一年的项目,因为我仍然是一名学位学生。
AUDIO_FILE = path.get()
r= sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio = r.record(source)
try:
filename = ".txt"
f = open( filename , "w+")
a = f.writelines(r.recognize_google(audio))
b = a.split("\n\n")
b[:] = (value for value in b if value is not '\t')
f.close()
except sr.UnknownValueError:
print("Google could not understand audio")
except sr.RequestError as e:
print("Google error; {0}".format(e))
return filename
也许你们知道如何编写一个数组来逐行从音频生成/写入文本文件。我再说一遍,我想要“逐行”。
这些是我得到的错误。请帮我。
b = a.split("\n\n")
AttributeError: 'NoneType' object has no attribute 'split'
最佳答案
您在 b = a.split("\n\n")
上的错误是因为您似乎认为 f.writelines()
会返回某些内容。事实并非如此,因此 a
的值为 None
并且无法拆分。
文档说明了 writelines()
的作用:
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
因此,如果您希望输出文件中有换行符,则必须在调用 writelines()
之前将它们放在那里。
但是您根本不应该调用 writelines()
,因为它需要一个字符串列表,而 recognize_google()
返回一个字符串。
由于您要获取一长串单词,并且每行需要 5 个单词,因此需要将文本分成包含 5 个单词的行,并为每行调用 write()
。像这样的事情:
recognized_text = r.recognize_google(audio)
remainder = recognized_text.split()
while remainder:
line, remainder = remainder[:5], remainder[5:]
f.write(' '.join(line) + "\n")
关于python - 使用音频的语音识别方法逐行写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729512/