使用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']
要檢查,如果在該字符串中存在的兩個詞,或者只是想有兩個字?你實際上已經有了這兩個字。他們是「全部」和「職員」:)你真的想要什麼? – Kent
@Kent對我來說,這完全清楚了提問者想要什麼。他想要一個正則表達式,在字符串中找到兩個單詞* total *和* staff *。沒有必要在我看來downvote。 – pemistahl
@PeterStahl好吧。即時通訊不是downvoter順便說一句。 :) – Kent