2012-12-17 67 views
1

我仍然在學習Python廣告正則表達式的繩索,我需要一些幫助! 我需要一個可以搜索特定單詞的正則表達式。 我已經設法創建一個模式來搜索一個單詞,但我如何檢索我需要找到的其他單詞? 重新模式將如何執行此操作?Python正則表達式來搜索一個語句中的單詞

>>> question = "the total number of staff in 30?" 
>>> re_pattern = r'\btotal.*?\b' 
>>> m = re.findall(re_pattern, question) 
['total'] 

它必須尋找詞「總」和「工作人員」 感謝 邁克

+0

要檢查,如果在該字符串中存在的兩個詞,或者只是想有兩個字?你實際上已經有了這兩個字。他們是「全部」和「職員」:)你真的想要什麼? – Kent

+0

@Kent對我來說,這完全清楚了提問者想要什麼。他想要一個正則表達式,在字符串中找到兩個單詞* total *和* staff *。沒有必要在我看來downvote。 – pemistahl

+0

@PeterStahl好吧。即時通訊不是downvoter順便說一句。 :) – Kent

回答

5

使用UNION操作|搜索所有你需要找到的話:

In [20]: re_pattern = r'\b(?:total|staff)\b' 

In [21]: re.findall(re_pattern, question) 
Out[21]: ['total', 'staff'] 

這與您最接近的示例相符。但是,這種方法僅適用於沒有其他字符被預置或附加到單詞的情況。在主要和從屬條款結尾處常常會出現這樣的情況,即逗號,點,感嘆號或問號附加在該條的最後一個單詞之後。

例如,在問題您的員工中有多少人?上面的方法找不到職員,因爲在職員的末尾沒有字邊界。相反,有一個問號。但是,如果你在上述正則表達式的結尾離開了第二\b,表達會錯誤地檢測單詞串,如完全totalities

來完成你想要什麼,最好的辦法是先提取您句子中的所有字母數字字符,然後搜索這個列表中,你需要找到的話:

In [51]: def find_all_words(words, sentence): 
....:  all_words = re.findall(r'\w+', sentence) 
....:  words_found = [] 
....:  for word in words: 
....:   if word in all_words: 
....:    words_found.append(word) 
....:  return words_found 

In [52]: print find_all_words(['total', 'staff'], 'The total number of staff in 30?') 
['total', 'staff'] 

In [53]: print find_all_words(['total', 'staff'], 'My staff is totally overworked.') 
['staff'] 
+0

這個。揍我吧嘿。 –

+0

謝謝Peter非常有幫助! –

+0

@MikeBarnes不客氣。 :)請考慮upvoting和接受我的答案,如果它解決了你的問題。 – pemistahl

1

有你,儘管使用的東西超出了正則表達式?

考慮這一點,如果它的作品從該解決方案擴大

>>> 'total' in question.split() 
True 

同樣

>>> words = {'total','staff'} 
>>> [e for e in words if e in question.split()] 
['total', 'staff'] 
+0

-1。這不是一個好的解決方案,因爲它只搜索字符串中的子字符串,並且不考慮顯然是提問者需要的字邊界。正則表達式中的特殊序列「\ b」彌補了這一點。 – pemistahl

+0

@PeterStahl:謝謝,我錯過了一個分割:-) – Abhijit

+0

只要使用'str.split()'也沒有幫助。那句話結尾的單詞怎麼樣?例如,在*「我們總共有多少人?」*您的解決方案找不到* total *這個詞,因爲在您的列表中只有* total * *。 – pemistahl

2
question = "the total number of staff in 30?" 
find=["total","staff"] 
words=re.findall("\w+",question) 
result=[x for x in find if x in words] 
result 
['total', 'staff'] 
相關問題