我在python中构建了一个简单的AI助手,到目前为止,一切都很好。语音识别和文本到语音的工作也很好。我想让它像,我要说一些东西,并根据输入,它会回答一些简单的问题。但是,对于if语句,我试图根据输入来创造条件,但是它不会被执行,相反,会执行else语句。
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
listener = sr.Recognizer()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty("rate", 178)
def talk(text):
engine.say(text)
print(text)
engine.runAndWait()
def command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
print(command)
except:
pass
command = ''
return command
def run():
data = command()
if 'hello' in data:
talk('Hello')
elif 'who are you' in data:
talk('I am an AI.')
else:
talk("I couldn't hear it.")
while True:
run()我尝试使用它没有功能,但仍然是相同的问题。即使if语句为真,它也不起作用。
发布于 2022-04-30 09:30:31
我想你想把command = ''放在除了块里。这是一个缩进错误。
https://stackoverflow.com/questions/72067178
复制相似问题