Python正则表达式搜索句子中的单词

Mik*_*nes 1 python regex

我仍在学习使用Python广告正则表达式的绳索,我需要一些帮助!我需要一个能够在句子中搜索特定单词的正则表达式.我设法创建一个模式来搜索单个单词,但我如何检索我需要找到的其他单词?重新模式将如何做到这一点?

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

它必须寻找"总"和"工作人员"的字样谢谢迈克

pem*_*ahl 7

使用union运算符|搜索您需要查找的所有单词:

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

In [21]: re.findall(re_pattern, question)
Out[21]: ['total', 'staff']
Run Code Online (Sandbox Code Playgroud)

这与您上面的示例最匹配.但是,此方法仅在没有其他字符已预先添加或附加到单词时才有效.在主要和从属子句的末尾经常出现这种情况,其中逗号,点,感叹号或问号被附加到该子句的最后一个单词.

例如,在问题中,您的员工中有多少人?上面的方法不会找到工作人员这个词,因为工作人员的最后没有字边界.相反,有一个问号.但是,如果你离开了第二\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']
Run Code Online (Sandbox Code Playgroud)