Skip to main content
 首页 » 编程设计

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

2025年05月04日22dyllove98

我仍在学习使用 Python 和正则表达式的技巧,我需要一些帮助! 我需要一个可以在句子中搜索特定单词的正则表达式。 我设法创建了一个模式来搜索单个词,但我如何检索我需要查找的其他词? re 模式如何执行此操作?

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

它必须寻找单词“total”和“staff” 谢谢 迈克

请您参考如下方法:

使用并集运算符| 来搜索所有需要查找的单词:

In [20]: re_pattern = r'\b(?:total|staff)\b' 
 
In [21]: re.findall(re_pattern, question) 
Out[21]: ['total', 'staff'] 

这最符合您上面的示例。然而,这种方法只有在没有其他字符被添加到单词之前或之后才有效。在主句和从句的末尾经常出现这种情况,其中逗号、点、感叹号或问号附加到从句的最后一个单词。

例如,在问题How many people are in your staff? 中,上述方法不会找到单词staff,因为末尾没有单词边界员工。相反,有一个问号。但是,如果您在上面的正则表达式末尾遗漏了第二个 \b,该表达式将错误地检测子字符串中的单词,例如 totally< 中的 total/em> 或总数。

完成你想要的最好的方法是先提取你句子中的所有字母数字字符,然后在这个列表中搜索你需要找到的词:

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']