【发布时间】:2019-11-29 18:59:31
【问题描述】:
完整代码
import speech_recognition as sr
adLoop = True
detector = sr.Recognizer()
with sr.Microphone() as source:
detector.adjust_for_ambient_noise(source)
print("Please speak: ")
audio = detector.listen(source)
print("Recognizing...")
final_text = detector.recognize_google(audio)
print(f"Converted speech: {final_text}")
while adLoop:
print("Would you like to convert more words to text?: Y/N")
test_audio = detector.listen(source)
test_text = detector.recognize_google(test_audio)
if test_text == "yes":
adLoop = True
print("go on")
audio_two = detector.listen(source)
print("Recognizing...")
final_text_two = detector.recognize_google(audio_two)
print(f"Current text: {final_text} {final_text_two}")
elif test_text == "no" and len(final_text_two) > 1:
adLoop = False
print(f"Everything is done, the final text looks like: {final_text} {final_text_two}")
elif test_text == "no":
adLoop = False
print(f"Everything is done, the final text looks like: {final_text}")
elif test_text != "yes" or "no":
print("Something went wrong...Please repeat(Answer Yes or No only)")
adLoop = True
您好,是否有可能检查 final_text_two 是否存在以防用户未输入,因此第 30 行可以在第 27 行之后工作。如果未输入 final_text_two,我目前收到错误消息。
if test_text == "yes":
adLoop = True
print("go on")
audio_two = detector.listen(source)
print("Recognizing...")
final_text_two = detector.recognize_google(audio_two)
print(f"Current text: {final_text} {final_text_two}")
elif test_text == "no" and len(final_text_two) > 1:
adLoop = False
print(f"Everything is done, the final text looks like: {final_text} {final_text_two}")
elif test_text == "no":
adLoop = False
print(f"Everything is done, the final text looks like: {final_text}")
【问题讨论】:
-
很容易检查变量是否存在,例如
"myvar" in vars(),但不要这样做,最好使用布尔标志,不要在变量的现有值上构建逻辑 -
明白了,求帮助。
标签: python python-3.x speech-recognition speech-to-text pyaudio