2016-10-02 2 views
-2

В настоящее время я создаю интерактивную систему, использующую python, способную понимать и отвечать. Следовательно, для этого существует множество условий для анализа и обработки машины. Напр. принять следующий код (только для справки):Есть ли способ удалить слишком много, если еще условия?

if ('goodbye') in message:       
     rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'] 
     speekmodule.speek(rand,n,mixer) 
     break 

    if ('hello') in message or ('hi') in message: 
     rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.'] 
     speekmodule.speek(rand,n,mixer) 

    if ('thanks') in message or ('tanks') in message or ('thank you') in message: 
     rand = ['You are wellcome', 'no problem'] 
     speekmodule.speek(rand,n,mixer) 

    if message == ('jarvis'): 
     rand = ['Yes Sir?', 'What can I doo for you sir?'] 
     speekmodule.speek(rand,n,mixer) 

    if ('how are you') in message or ('and you') in message or ('are you okay') in message: 
     rand = ['Fine thank you'] 
     speekmodule.speek(rand,n,mixer) 

    if ('*') in message: 
     rand = ['Be polite please'] 
     speekmodule.speek(rand,n,mixer) 

    if ('your name') in message: 
     rand = ['My name is Jarvis, at your service sir'] 
     speekmodule.speek(rand,n,mixer) 

Итак, есть ли способ, в котором я могу заменить все эти If Else условия ?? Потому что будет намного больше условий, и это сделает выполнение медленнее.

+1

Первым шагом является удаление ненужных парсеров, т. Е. Просто напишите 'if 'hello''. – skovorodkin

+0

Вот решение, использующее словари: http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python – imant

+0

Да, вы можете использовать словарь, как предлагается реализовать своего рода «переключатель ... случай ... ». Но с RegEx, чтобы реализовать «слово в сообщении». Однако это не уменьшит сложность вашего алгоритма: вы должны проверить все случаи. –

ответ

1

Сделать эксклюзивный "если":

if 'goodbye' in message:       
    rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'] 

elif 'hello' in message or 'hi' in message: 
    rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.'] 

elif 'thanks' in message or 'tanks' in message or ('thank you') in message: 
    rand = ['You are wellcome', 'no problem'] 

elif message == 'jarvis': 
    rand = ['Yes Sir?', 'What can I doo for you sir?'] 

elif 'how are you' in message or 'and you' in message or ('are you okay') in message: 
    rand = ['Fine thank you'] 

elif '*' in message: 
    rand = ['Be polite please'] 

elif 'your name' in message: 
    rand = ['My name is Jarvis, at your service sir'] 

else: 
    raise NotImplementedError("What to do?") 

speekmodule.speek(rand, n, mixer) 

С отображением RegEx:

mapping = { 
    r"\bgoodbye\b": ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'], 
    r"\bhello\b": ['Wellcome to Jarvis virtual intelligence project. At your service sir.'], 
    ...} 

for regex, rand in mapping.items(): 
    if re.search(message, flags=re.I): 
     break 
else: 
    raise NotImplementedError("What to do?") 
speekmodule.speek(rand, n, mixer) 

Это до вас, чтобы решить.

0

if/elif/else - это естественный способ структурирования такого кода в Python. Как отметил @imant, вы можете использовать основанный на dict подход в случае простого ветвления, но я вижу в вашей предикате if некоторую довольно сложную логику, поэтому вам придется проверять все предикаты в любом случае, и вы не будете иметь никакой производительности выигрыш с другой структурой кода.

Хотя это может быть немного более удобным для чтения и легче поддерживать, если учитывать ваши предикаты и действия, как это:

from collections import OrderedDict 

def goodbye_p(message): 
    return 'goodbye' in message 

def goodbye_a(): 
    rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'] 
    # As @Moinuddin Quadri I also assume that your `speek` method 
    # says random message from a list. 
    # Otherwise you can use `random.choice` method 
    # to get a random message out of a list: `random.choice(messages)`. 
    speekmodule.speek(rand, n, mixer) 


def hello_p(message): 
    return 'hello' in message or 'hi' in message 

def hello_a(): 
    rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.'] 
    speekmodule.speek(rand, n, mixer) 

# Use `OrderedDict` instead of `dict` to control order 
# of checks and actions. 
branches = OrderedDict([ 
    # (predicate as key, action as value) 
    (goodbye_p, goodbye_a), 
    (hello_p, hello_a), 
]) 

for predicate, action in branches.items(): 
    if predicate(message): 
     action_result = action() 
     # You can add some logic here based on action results. 
     # E.g. you can return some special object from `goodbye_a` 
     # and then shut down Jarvis here. 
     # Or if your actions are exclusive, you can add `break` here. 

Если все предикаты одинаковы и содержат только подстроки проверки, то это может быть более эффективным, чтобы иметь кортежи (например, ('hello', 'hi')) в виде ключей dict. Тогда вы можете перебирать эти ключи, как это:

for words, action in branches.items(): 
    if any(word in message for word in words): 
     action() 
0

Во-первых, создать dict объект с ключом, как tuple строки вы хотите, чтобы соответствовать вашей message и связать его со значением string которой ваш Джарвис предполагают, чтобы ответить , Например:

jarvis_dict = { 
    ('goodbye',) : ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'], 
    ('hello', 
    'hi')  : ['Wellcome to Jarvis virtual intelligence project. At your service sir.'], 
    ('thanks', 
    'tanks', 
    'thank you') : ['You are wellcome', 'no problem'], 
    ('jarvis',) : ['Yes Sir?', 'What can I doo for you sir?'], 
    ('how are you', 
    'and you', 
    'are you okay'): ['Fine thank you'], 
    ('*',)  : ['Be polite please'], 
    ('your name',): ['My name is Jarvis, at your service sir'] 
} 

Теперь итерацию каждый ключ из вас dict проверить любой подстрока, является ли часть сообщения, и если есть какие-либо матч, вызовите функцию speekmodule.speek(rand,n,mixer) как:

for key, value in jarvis_dict.items(): 
    if any(item in message for item in key): 
     speekmodule.speek(value, n, mixer) 

Примечание: Здесь я предполагаю, что speekmodule.speek(value, n, mixer) в вашем коде работает так как в вашем коде отсутствует информация о декларации. Я только что заменил ваш randvalue так же, как и тот же список str, который возвращает dict, который используется в вашем коде.

+0

Вы, вероятно, хотели бы использовать 'random.choice (value)', чтобы получить случайный ответ из набора предопределенных вариантов. – skovorodkin

+2

Как я уже упоминал в ответе, я не уверен, как работает функция 'speekmodule.speek()', и я предполагаю, что эта функция в OP работает нормально (и вызывается 'random.choice (value)' внутри функции '.pepe()'). Мой код предназначен для обеспечения той же функциональности, что и OP. –

0

Использование словаря:

someCollections = { 
    'goodbye': "Something1", 
    'hello': "Somthing2", 
    ... 
} 

speekmodule(someCollections [SomeKey],...) 
+3

Неправильная практика использования встроенных имен (например, 'dict') для переменных. – Dartmouth

+0

Ответ обновлен. – David