我仍在学习 Python 和正则表达式的诀窍,我需要一些帮助!
我需要一个可以在句子中搜索特定单词的正则表达式。
我已经成功创建了一个模式来搜索单个单词,但是如何检索我需要查找的其他单词?
重新模式会是什么样子来做到这一点?
>>> 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']
这与您上面的示例最接近。但是,此方法仅在没有其他字符已添加到单词之前或附加的情况下才有效。这种情况通常发生在主句和从句的末尾,其中逗号、点、感叹号或问号附加到子句的最后一个单词上。
例如,在问题中你们的员工有多少人?上面的方法找不到这个词staff因为末尾没有单词边界staff。相反,有一个问号。但如果你省略第二个\b
在上面的正则表达式末尾,该表达式会错误地检测子字符串中的单词,例如total in totally or 总体性.
实现您想要的效果的最佳方法是首先提取句子中的所有字母数字字符,然后在此列表中搜索您需要查找的单词:
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']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)