优化代码 import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes listener = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) 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 'assistant' in command: command = command.replace('assistant', '') print(command) except: pass return command def run_assistant(): command = take_command() print(command) if 'play' in command: song = command.replace('play', '') talk('playing ' + song) pywhatkit.playonyt(song) elif 'time' in command: time = datetime.datetime.now().strftime('%I:%M %p') talk('Current time is ' + time) elif 'who is' in command: person = command.replace('who is', '') info = wikipedia.summary(person, 1) print(info) talk(info) elif 'joke' in command: talk(pyjokes.get_joke()) else: talk('Please say the command again.') while True: run_assistant()
时间: 2024-02-14 11:17:05 浏览: 153
以下是对代码的一些优化建议:
1. 对于异常处理,建议在异常发生时打印出错误信息,方便排查问题。例如:
```python
except Exception as e:
print(f"Error: {e}")
```
2. 在`take_command()`函数中,如果出现无法识别语音的情况,建议给用户一些提示信息,例如:
```python
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'assistant' in command:
command = command.replace('assistant', '')
print(command)
except sr.UnknownValueError:
print("Sorry, I didn't catch that. Could you please say it again?")
talk("Sorry, I didn't catch that. Could you please say it again?")
command = ""
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service: {e}")
command = ""
return command
```
3. 在`run_assistant()`函数中,建议对语音指令进行更严格的判断。例如,如果用户说了“play”,但没有指定歌曲名称,那么就会出现错误。可以通过判断语音指令中是否包含必要的参数来避免这种情况。例如:
```python
def run_assistant():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '').strip() # 去掉前后空格
if song:
talk('playing ' + song)
pywhatkit.playonyt(song)
else:
talk("Sorry, please specify a song name to play.")
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who is' in command:
person = command.replace('who is', '').strip() # 去掉前后空格
if person:
info = wikipedia.summary(person, 1)
print(info)
talk(info)
else:
talk("Sorry, please specify a person's name.")
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Sorry, I did not understand that. Please say the command again.')
```
4. 最后一个建议是,可以将一些常用的语音指令保存到一个字典中,然后在`run_assistant()`函数中进行匹配,这样可以使代码更简洁。例如:
```python
COMMANDS = {
'play': lambda song: pywhatkit.playonyt(song),
'time': lambda: datetime.datetime.now().strftime('%I:%M %p'),
'who is': lambda person: wikipedia.summary(person, 1),
'joke': lambda: pyjokes.get_joke()
}
def run_assistant():
command = take_command()
print(command)
for key in COMMANDS:
if key in command:
args = command.replace(key, '').strip() # 去掉前后空格
if args:
talk(COMMANDS[key](args))
else:
talk("Sorry, please specify the command argument.")
break
else:
talk('Sorry, I did not understand that. Please say the command again.')
```
这样就可以通过一个`COMMANDS`字典来管理所有的语音指令,代码也更加简洁。
阅读全文