【问题标题】:A problem in my code, how to check if variable exists or not我的代码中的一个问题,如何检查变量是否存在
【发布时间】: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


【解决方案1】:

我不确定该库是如何工作的,但您可能可以使用 try 和 except。

try:
     print(f"Everything is done, the final text looks like: {final_text} {final_text_two}")

except:
    print("Nothing entered.")

【讨论】:

  • 呃,我的错。现在 while 循环没有结束,它没有工作。
猜你喜欢
  • 2011-10-29
  • 2020-09-25
  • 2011-08-16
  • 2013-08-12
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
相关资源
最近更新 更多