2016-02-18 92 views
1

我正在使用一個語音識別庫來創建一個類似Siri的程序。我希望將來我可以使用Arduino的代碼來控制房間周圍的事物。這裏是我的問題:Python if if,elif,else chain

我有基本的語音識別代碼,但爲了理解某些命令的程序,我將不得不通過很長的if-elif-elif-elif-else命令列表來運行語音和這可能會很慢。由於大部分時間都會導致else,因爲命令不會被識別,所以我需要更快的替代if-elif-else語句的長鏈。我也正在使用一個tts引擎與你交談。

這裏是我到目前爲止的代碼

import pyttsx 
import time 


engine = pyttsx.init() 
voices = engine.getProperty("voices") 
spch = "There is nothing for me to say" 
userSaid = "NULL" 



engine.setProperty("rate", 130) 
engine.setProperty("voice", voices[0].id) 


def speak(): 
    engine.say(spch) 
    engine.runAndWait() 
def command(): 
    **IF STATEMENT HERE** 

r = sr.Recognizer() 
with sr.Microphone() as source: 
    r.adjust_for_ambient_noise(source) 
    print("CaSPAR is calibrated") 
    audio = r.listen(source) 
try: 
    userSaid = r.recognize_google(audio) 
except sr.UnknownValueError: 
    spch = "Sorry, I did'nt hear that properly" 
except sr.RequestError as e: 
    spch = "I cannot reach the speech recognition service" 

speak() 
print "Done" 
+2

歡迎來到Stack Overflow。你的問題是_Too Broad_:有太多可能的答案,或者這個格式的答案太長。請添加詳細信息以縮小答案集或隔離幾個段落中可以回答的問題。請參閱http://stackoverflow.com/help/how-to-ask – Selcuk

+2

我們需要更多地瞭解您的代碼如何工作以提供合理的答案 –

+1

請查看Aya提供的答案,以解答之前提出的類似問題:http: //stackoverflow.com/questions/17166074/most-efficient-way-of-making-an-if-elif-elif-else-statement-when-the-else-is-don – abhi

回答

2

嘗試使用字典設定,其中,關鍵是你正在測試和該鍵的條目是處理函數的值。一些關於Python的教科書指出,這是比一系列if ... elif語句更優雅的解決方案,並立即獲取條目,而不必測試每種可能性。請注意,因爲每個鍵都可以是任何類型,所以這比C中的switch語句更好,這需要switch參數和case爲整數值。例如。

def default(command) 
    print command, ' is an invalid entry' 

mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate} 

action = mydict.get(command, default) 
# set up args from the dictionary or as command for the default. 
action(*args) 

有趣的一點是,Most efficient way of making an if-elif-elif-else statement when the else is done the most?指出,雖然得到的是更多的「高雅」,它實際上可能比下面的代碼慢。但是,這可能是因爲該帖子處理直接操作而不是函數調用。 YMMV

def default(command) 
    print command, ' is an invalid entry' 

mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate} 

if command in mydict: 
    action = mydict.[command] 
    # set up args from the dictionary . 
    action(*args) 
else: 
    default(command) 
+0

而不是檢查密鑰是否存在,可以使用缺省值的字典的'.get'方法,比如no-op lambda或者通知打印聲明。 – cat

+1

@cat完成。這就是爲什麼我添加了關於設置參數的評論。 – sabbahillel

+0

@cat我還指出了一個職位,比較兩種方法,只要時機進行並將該信息添加到帖子中。 – sabbahillel