2010-10-09 20 views
6

假設我要求用戶輸入原始數據,他們說:「這是一條消息。」如果那個原始輸入包含單詞「消息」,那麼它會在那之後執行一個動作。我能否看到如何做到這一點?如何檢查句子是否包含Python中的某個單詞,然後執行操作?

+2

如果你嘗試建立一個內容過濾器,可以這樣考慮:單詞「經典」有「屁股」,在它(其中,順便說一句是驢的另一種說法) 。這當然只是一個樣本 - – knitti 2010-10-09 21:36:50

回答

7

外出時根據由@knitti評論,問題是,你需要首先分割句成詞,然後檢查:

term = "message" #term we want to search for 
input = raw_input() #read input from user 

words = input.split() #split the sentence into individual words 

if term in words: #see if one of the words in the sentence is the word we want 
    do_stuff() 

否則,如果你有一句「這是一個經典「並且你試圖檢查它是否包含單詞」ass「,它會錯誤地返回True。

當然,這仍然不是完美的,因爲那樣你可能不得不擔心諸如刪除標點符號之類的東西,而不是(比如,等等),否則句子「那一個是經典的」。仍然會返回False來尋找「經典」(因爲最後的時期)。而不是推倒重來,這裏是一個很好的職位上的Python從一個句子剝離標點符號:

Best way to strip punctuation from a string in Python

有區分大小寫考慮太多,所以您可能要改變raw_input結果與你的搜索詞小寫,然後再進行搜索。只需使用str類中的lower()函數即可輕鬆完成此操作。

這些問題似乎總是簡單...

0
if "message" in sentence: 
    do_action() 
+0

謝謝你!給我這個答案後,我有點感到蠢。 – 2010-10-09 21:37:46

+2

由於子字符串匹配的情況,這將不起作用。 – DehengYe 2016-03-23 05:41:36

1

當然,這是一個很簡單的例子:

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) 

請注意,這也爲輸入不包含任何觸發字時的情況定義了默認操作。

查看here瞭解上述映射習語的更多細節,這實際上是Python實現'switch語句'的方式。

相關問題