如果有条件,程序将首先执行

时间:2019-06-10 04:15:23

标签: python-3.x speech-recognition text-to-speech pyttsx

我正在尝试在python中构建语音识别应用,一切正常,但是,无论输入什么,在执行程序时始终执行第一个If条件。

import speech_recognition as sr
from gtts import gTTS
import os
from google_speech import Speech
import webbrowser

def speech():
    while True:
        try:
            with sr.Microphone() as source:

                r = sr.Recognizer()
                audio = r.listen(source,timeout=3, phrase_time_limit=3)
                x = r.recognize_google(audio)
                print(x)
                if 'hello' or 'Hello' or 'Hi' in x:
                    speech=Speech('Hello,How are you?','en')
                    speech.play()           

                    print('Input: ',x)
                    print('output: Hello,How are you?',)

                elif 'omkara' or 'Omkara' in x:
                    speech=Speech('Playing Omkara song on Youtube','en')
                    speech.play()

                    webbrowser.get('/usr/bin/google-chrome').open('https://youtu.be/NoPAKchuhxE?t=21')

        except sr.UnknownValueError:
            print("No clue what you said, listening again... \n")
            speech()


if __name__ == '__main__':
    print('Executine Voice based commands \n')
    speech()

这是我用来连续重复执行该程序的代码,但是,首先要确定条件,只有在输入中有“ Hello”,“ Hi”时才执行。第一次我说“嗨”,那么它是否有效,但是当程序再次循环输入“你好吗”之类的代码时,它仍然会执行第一个IF条件,有人可以帮助我。谢谢。

2 个答案:

答案 0 :(得分:2)

您在此错误地使用了or。尝试使用以下代码:

if any(check in x for check in ('hello', 'Hello', 'Hi')):

答案 1 :(得分:2)

发生问题是因为if 'Hello'立即变为True。条件成立后,它将始终转到if条件。

您可以尝试使用bool('Hello')进行检查。解决方案是分别检查每个字符串。

if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
    something
相关问题