【发布时间】:2021-05-30 08:42:28
【问题描述】:
我正在用 python 构建一个桌面助手。
if 条件和前两个 Elif 条件只是文件,但是当我尝试调用第四个 Elif 条件时,无论我如何更改条件,它都会自动调用第三个 Elif 条件。
我尝试用第四个 Elif 替换第三个 Elif,但仍然在第三个位置执行 Elif。
这是我的代码...... run() 函数中存在问题
# region Importing Modules
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
# endregion
gender=0
rate = 190
listener = sr.Recognizer()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[gender].id)
def speak(text):
engine.setProperty('rate', rate)
engine.setProperty('voice', voices[gender].id)
engine.say(text)
engine.runAndWait()
def tk_command():
with sr.Microphone() as source:
print("listening...")
listener.adjust_for_ambient_noise(source)
voice = listener.listen(source)
try:
command = listener.recognize_google(voice, language="en-in")
command=str(command)
return command
except Exception as e:
speak("Didn't hear anything, try again.")
tk_command()
def hotword():
global gender
command = tk_command()
if 'jarvis' in command.lower():
gender=1
speak("Jarves, hey buddy. You're up.")
gender=0
speak('Well, I am here to assist')
print (command)
run()
elif 'friday' in command.lower():
gender=0
speak("Hey Friday, it's your call")
gender=1
speak('Ok, how can I assist')
print (command)
run()
def anything_else(): #### Check if this works ####
speak("Any other service I can do ?")
command=tk_command()
command.lower()
if 'no' or 'nope' or 'nah' or 'na' in command:
speak("Ok. Happy to help.")
print(command)
hotword()
elif command == 'yes' or command == 'yeah' or command == 'yup':
speak("Ok. Just ask me.")
run()
else:
speak("Sure...")
run(command, True)
def run(command=None, check=False):
global rate
# region Taking command input
if check == False:
command = tk_command()
command = command.lower()
command = command.replace('friday', '')
command = command.replace('Jarvis', '')
# endregion
''' Functioning of various commands are describes below
as multiple elif statements '''
if ('play' or 'search') and 'youtube' in command and 'google' not in command: # Play or search on youtube
song = command.replace('play', '')
song = song.replace('youtube', '')
song = song.replace('on', '')
song = song.replace('for', '')
speak('Playing.'+ song)
pywhatkit.playonyt(song)
elif ('send' or 'message') and 'whatsapp' in command: # Sending a Whatsapp message
if 'to' not in command: # Check if phone number is input
speak('''Please say the command with a phone number or a contact name.
To save a new contact say, Save... your phone number...
as... name of the recepient.''')
else: # Else Send the message
command = command.replace('send', '')
command = command.replace('whatsapp', '')
command = command.replace('message', '')
command = command.replace('to', '')
command = command.replace('on', '')
try:
number = int(command.replace(' ',''))
speak("Sure, what's the message.")
message = tk_command()
pywhatkit.sendwhatmsg_instantly(f"+91{number}", message)
except Exception as e:
speak('Invalid number or contact, please try again.')
print (command)
run()
elif 'time' in command: # Asking what time is it
time = datetime.datetime.now().strftime('%I:%M:%S %p')
speak('Right now, its, '+ time)
elif 'search google for' or ('search' and 'on google') in command: # Searches anything on google
print('Google Search')
command=command.replace('search google for', '')
command=command.replace('search', '')
command=command.replace('on google', '')
command=command.replace(' ', '+')
pywhatkit.search(command)
elif (('who' or 'what') and 'is') or 'wikipedia' in command: # Searches wikipedia for anything or anyone
print(command)
print('Wikipedia Search')
lines = 1
if 'explain' in command:
lines = 3
command = command.replace('explain', '')
command = command.replace('who', '')
command = command.replace('what', '')
command = command.replace('is', '')
info = pywhatkit.info(command, lines)
rate -= 20
speak(info)
rate += 20
else: # Exits the program
speak('Exiting the program.')
sys.exit()
anything_else()
hotword()
【问题讨论】:
-
不确定这是否只是问题或代码中的问题。但是
if...elif... 与您的def run()处于同一缩进级别,因此它们不是该功能的一部分 -
@derpirscher 抱歉格式化,这是在发布问题时发生的。 if、elif 和 else 语句在我的代码编辑器中的 def run() 内完美对齐。
标签: if-statement conditional-statements desktop assistant