Python正则表达式可搜索句子中的单词
问题内容:
我仍在学习Python广告正则表达式的知识,请帮忙!我需要一个可以在句子中搜索特定单词的正则表达式。我设法创建了一个模式来搜索单个单词,但是如何检索需要查找的其他单词呢?re模式看起来如何做到这一点?
>>> question = "the total number of staff in 30?"
>>> re_pattern = r'\btotal.*?\b'
>>> m = re.findall(re_pattern, question)
['total']
它必须查找单词“ total”和“ staff”,谢谢Mike
问题答案:
使用并运算符|
搜索您需要查找的所有单词:
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']