0

我正在尝试在 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”时执行。我第一次说“嗨”,如果是有效的,但是当程序再次循环输入另一个输入,比如“你好吗”时,它仍然执行第一个 IF 条件,任何人都可以帮我解决这个问题。谢谢。

4

2 回答 2

2

or在那里以错误的方式使用。尝试使用此代码:

if any(check in x for check in ('hello', 'Hello', 'Hi')):
于 2019-06-10T04:24:39.140 回答
2

The problem occurs because if 'Hello' becomes True instantly. Once you have a condition which is true, it will always go to if condition.

You can try to check this using bool('Hello'). The solution is to check each string separately.

if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
    something
于 2019-06-10T04:25:27.110 回答