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

时间:2012-12-17 11:43:35

标签: python regex

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

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

必须找“总”和“员工”这几个字 谢谢 麦克

3 个答案:

答案 0 :(得分:6)

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

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

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

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

例如,在问题你的员工中有多少人?上面的方法找不到单词 staff ,因为最后没有单词边界员工相反,有一个问号。但是如果你在上面的正则表达式的末尾省略了第二个\b,表达式将错误地检测子串中的单词,例如 中的 total 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']

答案 1 :(得分:2)

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

答案 2 :(得分:1)

你有没有使用Regex以外的东西?

考虑这一点,如果它可以从这个解决方案扩展

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

类似地

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