我正在以siri和谷歌助手的形式构建一个弱Ai平台,然而,每次我运行代码时,它总是返回"对不起,我没有捕捉到"——这是一个例外,而不是通过麦克风接收输入。我正在遵循YouTube教程来构建这个,因为我对python还很陌生,因此我不知道问题是什么,因为它似乎对教程中的人很有效。有人能帮我把这个修好吗?感谢
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import pythoncom
print("Initializing Karren")
MASTER = "Nadeem"
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(text):
engine.say(text)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour <12:
speak("Good Morning" + MASTER)
elif hour>=12 and hour<18:
speak("Good Afternoon" + MASTER)
else:
speak("Good Evening" + MASTER)
speak("How may I assist you?")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try :
print("Recognizing...")
query = r.recognize_google(audio, language ='en-uk')
print(f"user said: {query}n")
except Exception as e:
print("Sorry i didn't catch that...")
speak("Initializing Karren...")
wishMe()
query = takeCommand()
#Logic
if query:
if 'wikipedia' in query.lower():
speak('Searching wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences =2)
print(results)
speak(results)
if 'open youtube' in query.lower():
webbrowser.open("youtube.com")
好吧,这是更新后的代码@iSavageSkull
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import pythoncom
print("Initializing Karren")
MASTER = "Nadeem"
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(text):
engine.say(text)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour <12:
speak("Good Morning" + MASTER)
elif hour>=12 and hour<18:
speak("Good Afternoon" + MASTER)
else:
speak("Good Evening" + MASTER)
speak("How may I assist you?")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try :
print("Recognizing...")
query = r.recognize_google(audio, language ='en-uk')
print(f"user said: {query}n")
except Exception as e:
print("Sorry i didn't catch that...")
speak("Initializing Karren...")
wishMe()
query = takeCommand()
#Logic
if query:
if 'wikipedia' in query.lower():
speak('Searching wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences =2)
print(results)
speak(results)
if 'open youtube' in query.lower():
webbrowser.open("youtube.com")
您在此处犯的错误:
在
def takeCommand()
下,print(f"user said: {query}n")
缩进错误,应该正确缩进。在相同的
def takeCommand()
下,
except Exception as e:
print("Sorry i didn't catch that...")
在这里,它是和缩进错误,这就是为什么它总是打印错误,即使代码正在产生合法的输出
运行我更新的代码,程序运行良好!!!