大家好,我正在尝试开发一个虚拟助手,它可以帮助我完成一些项目,所以我试图获得最终项目的基础知识,但是我收到一个错误(UnboundLocalError:分配前引用的局部变量“命令”)和我试图将 return command
更改为 printf(command)
下,但它不让我说话,并且一条消息 NONE 和另一个错误(TypeError: argument of type 'NoneType' is not iterable)出现在终端。
那么我怎样才能不停地工作呢?
代码如下:
import pyttsx3
import pywhatkit
import datetime
listener = sr.Recognizer()
engine = pyttsx3.init()
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'skor' in command:
command = command.replace ('skor', '')
print(command)
except:
pass
return command
def run_skor():
command = take_command()
print(command)
if 'play on youtube' in command:
song = command.replace ('play on youtube', '')
talk('playing' + song)
pywhatkit.playonyt(song)
elif 'search on google' in command:
sea = command.replace ('search on google', '')
talk ('searching' + sea)
pywhatkit.search(sea)
elif 'tell me the time' in command:
time = datetime.datetime.now().strftime('%H:%M')
print(time)
talk('Current time is' + time)
while True:
run_skor()```
答案 0 :(得分:0)
您需要进行的唯一更改是在 take_command()
函数中。这是我的版本:
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'skor' in command:
command = command.replace ('skor', '')
print(command)
except sr.UnknownValueError:
command = ""
return command
基本上,您可以先更改 execpt 命令,更具体地说。 sr
有一个名为 UnknownValueError
的内置命令。我们可以使用它来更具体地了解except命令何时起作用。然后,在 except
中,将命令设置为 ""
。这将停止错误,因为当命令返回时,它仍然是一个字符串,并且仍然有效。
答案 1 :(得分:0)
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
print("Recognizing...")
command = r.recognize_google(audio, language='en-in')
print(f"User said: {command}\n")
except Exception as e:
print("Say that again please...")
return "None"
return command.lower()