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

2024-05-15 00:55:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍然在学习Python和正则表达式的诀窍,我需要一些帮助,请! 我需要一个正则表达式,它可以在一个句子中搜索特定的单词。 我已经创建了一个模式来搜索一个单词,但是如何检索我需要查找的其他单词呢? 重新设计的模式会是什么样子?

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

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


Tags: oftheinrenumber模式单词句子
3条回答

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

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

In [21]: re.findall(re_pattern, question)
Out[21]: ['total', 'staff']

这与上面的例子最为吻合。但是,这种方法只在没有其他字符被添加到单词的前面或后面时才有效。这种情况经常出现在主句和从句的末尾,在主句和从句的最后一个字后面加上逗号、点、感叹号或问号。

例如,在这个问题上,你的员工有多少人?上述方法找不到单词staff,因为在staff结尾没有单词边界。相反,这里有一个问号。但是如果在正则表达式的末尾省略第二个\b,则表达式将错误地检测子字符串中的单词,例如totalintotaltotalities

最好的方法是先提取句子中的所有字母数字字符,然后在此列表中搜索需要查找的单词:

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']
question = "the total number of staff in 30?"
find=["total","staff"]
words=re.findall("\w+",question)
result=[x for x in find if x in words]
result
['total', 'staff']

你想不想用Regex以外的东西?

考虑一下,如果它有效,就从这个解决方案中展开

>>> 'total' in question.split()
True

类似地

>>> words = {'total','staff'}
>>> [e   for e in words if e in question.split()]
['total', 'staff']

相关问题 更多 >

    热门问题