这当然是一个非常简单的例子:
if "message" in raw_input():
action()
如果你被要求将不同的单词映射到不同的动作,那么你可以这样做:
# actions
def action():
print "action"
def other_action():
print "other action"
def default_action():
print "default action"
# word to action translation function
def word_to_action(word):
return {
"message": action,
"sentence": other_action
}.get(word, default_action)()
# get input, split into single words
w = raw_input("Input: ").split()
# apply the word to action translation to every word and act accordingly
map(word_to_action, w)
请注意,这还定义了输入不包含任何触发词时的默认操作。
请参阅此处了解有关上述映射习惯用法的更多详细信息,这实际上是Python实现switch语句的方法。