在python中创建语音助手,并给它一个while循环,这样我就可以给它另一个命令,但是当它不识别我的单词时,它就结束了



嗨我正在用python做一个语音助手我已经做了一个while循环这样在我问了一个问题或说了一个命令之后我可以再问一遍,它可以工作但问题是如果它不能识别我说的话它会退出并给我一个错误

我试着看一些youtube教程,但他们都使用不同的变量和代码比我,所以我找不到解决方案,也不能找到修复堆栈溢出…

下面是我使用的代码

import speech_recognition as sr
import pyaudio
import wikipedia
import datetime
import webbrowser as wb
import pywhatkit
import os
from requests import get

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.runAndWait()

def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()

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-in')
print(f"user said: {query}n")
except Exception as e:
print("Sorry i didn't catch that...")
return query

def wish():
hour = datetime.datetime.now().hour
if hour >= 6 and hour < 12:
speak("Good Morning Sir!")
elif hour >= 12 and hour < 18:
speak("Good after noon Sir!")
elif hour >= 18 and hour < 24:
speak("Good evening Sir!")
else:
speak("Good night sir")
speak("I am jarvis your personal assistant")

def time():
Time = datetime.datetime.now().strftime("%I:%M:%S")
speak(Time)

def date():
year = int(datetime.datetime.now().year)
month = int(datetime.datetime.now().month)
date = int(datetime.datetime.now().day)
speak(date)
speak(month)
speak(year)

if __name__ == "__main__":
wish()
while True:
query = takeCommand()
if 'according to wikipedia' in query.lower():
speak('Searching wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak(results)
if 'open youtube' in query.lower():
wb.open('https://youtube.com')
if 'open google' in query.lower():
wb.open('https://google.com')
if 'open reddit' in query.lower():
wb.open('https://reddit.com')
if 'open amazon' in query.lower():
wb.open('https://amazon.ae')
if 'open wikipedia' in query.lower():
wb.open('https://wikipedia.com')
if 'open discord' in query.lower():
wb.open('https://discord.com/channels/@me')
if 'open gmail' in query.lower():
wb.open('https://gmail.com')
if 'open twitter' in query.lower():
wb.open('https://twitter.com')
if 'what time is it' in query.lower():
speak(time())
if 'what is the day' in query.lower():
speak(date())
if 'search' in query.lower():
search = query.replace('search', '')
speak('searching ' + search)
pywhatkit.search(search)
if 'play' in query.lower():
song = query.replace('play', '')
speak('playing ' + song)
pywhatkit.playonyt(song)
if "launch notepad" in query.lower():
npath = "C:\WINDOWS\system32\notepad.exe"
os.startfile(npath)
if "launch discord" in query.lower():
npath = "C:\Users\Yousif\AppData\Local\Discord\Update.exe"
os.startfile(npath)
if "launch steam" in query.lower():
npath = "C:\Program Files (x86)\Steam\steam.exe"
os.startfile(npath)
if "launch epic games" in query.lower():
npath = "C:\Program Files (x86)\Epic Games\Launcher\Portal\Binaries\Win32\EpicGames.exe"
os.startfile(npath)
if "what is my ip" in query.lower():
ip = get('https://api.ipify.org').text
speak(f"your IP Address is {ip}")
print(ip)
if 'hey jarvis' in query.lower():
speak("I am here sir")
print("I am here sir")
if 'thank you' in query.lower():
speak("your welcome sir")
if 'sleep' in query.lower():
speak("good bye sir")
exit()```
---
And here's the error I got
```Traceback (most recent call last):
File "C:/Users/PycharmProjects/Jarvis Mk2/main.py", line 72, in <module>
query = takeCommand()
File "C:/Users/PycharmProjects/Jarvis Mk2/main.py", line 37, in takeCommand
return query
UnboundLocalError: local variable 'query' referenced before assignment
Process finished with exit code 1```

return关键字在try...except之外。但是query只在try...block中定义。如果发生异常,则在代码移动到except Exception:块时不定义异常。然后,执行return查询,但是query没有被赋值。

return...移动到try...block

while True:
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"user said: {query}n")
return query
except Exception as e:
print("Sorry i didn't catch that...")

同样,使用while循环,它将继续循环,直到遇到返回关键字

问题出在你的try.. expept子句上。如果您的命令不能被识别,则会触发expect子句,但是在它打印"Sorry, I didn't catch that"之后,您仍然要求它返回queryquery只有在try分支执行成功的情况下才会被赋值。因此你会得到UnboundLocalError。要避免这种情况,请尝试:

try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"user said: {query}n")
except Exception as e:
print("Sorry i didn't catch that...")
return ""
return query

这将在不强制query值的情况下退出。这也会导致while循环中的所有if语句计算为false(试图处理它不理解的查询是不明智的,因此跳过所有if是理想的行为)。但是,您可能想要考虑返回None,并在while-loop中以不同的方式处理这种情况(注意:与None或像query isis not None而不是==操作符进行比较)。

同时,欢迎来到stackoverflow,祝你住得愉快:)希望这对你有帮助,

——

如果你看这个函数:

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-in')
print(f"user said: {query}n")
except Exception as e:
print("Sorry i didn't catch that...")
return query

query变量只有在时才定义r.recognize_google(audio, language='en-in')成功。如果失败,则没有定义query。但是你仍然试图在函数结束时返回它。

两个解决方案:

  • 在函数开头设置query = None
  • 或者return Noneexcept块内

相关内容

最新更新