程序保持先执行if条件

program keeps executing first if condition

我正在尝试在 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()

这是我在不断重复程序时使用的代码,但是,在第一个if条件下,它应该只在输入有'Hello'、'Hi'时执行。我第一次说 'Hi',if 是有效的,但是当程序再次使用另一个输入(如 'how are you' 循环时,它仍然执行第一个 IF 条件,任何人都可以帮助我 this.Thank 你。

你在那里使用 or 的方式不对。尝试使用此代码:

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

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

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

if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
    something