在 Python3 中的字符串中查找所有出现的单词

Finding all occurrences of a word in a string in Python3

我试图在 1 个句子中找到所有包含 "hell" 的单词。下面的字符串出现了 3 次。但是 re.search 只返回前 2 次。我尝试了 findall 和搜索。有人可以告诉我这里有什么问题吗?

>>> s = 'heller pond hell hellyi'
>>> m = re.findall('(hell)\S*', s)
>>> m.group(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'group'
>>> m = re.search('(hell)\S*', s)
>>> m.group(0)
'heller'
>>> m.group(1)
'hell'
>>> m.group(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group
>>> 

你可以用str.split看看子串是否在每个单词中:

s = 'heller pond hell hellyi'

print([w for w in s.split() if "hell" in w])

您的正则表达式未找到 hell,因为您只匹配位于其他非 space 字符之前的 hell。相反,只需查找文字 hell——没什么特别的。

In [3]: re.findall('hell', 'heller pond hell hellyi')
Out[3]: ['hell', 'hell', 'hell']

编辑

根据您的评论,您想要 return 整个单词(如果它位于单词的中间)。在这种情况下,您应该使用 * 零个或多个量词。

In [4]: re.findall(r"\S*hell\S*", 'heller pond hell hellyi')
Out[4]: ['heller', 'hell', 'hellyi']

换句话说:

re.compile(r"""
    \S*          # zero or more non-space characters
    hell         # followed by a literal hell
    \S*          # followed by zero or more non-space characters""", re.X)

请注意,Padraic 的回答绝对是解决此问题的最佳方式:

[word for word in "heller pond hell hellyi".split() if 'hell' in word]

您可以使用 re.findall 并搜索 hell 两边有零个或多个单词字符:

>>> import re
>>> s = 'heller pond hell hellyi'
>>> re.findall('\w*hell\w*', s)
['heller', 'hell', 'hellyi']
>>>

也许是我,但我很少使用正则表达式。 Python3 具有丰富的文本函数,使用内置函数有什么问题?

'heller pond hell hellyi'.count('hell')

我看到的唯一缺点是这样我从未真正学会使用正则表达式。 :-)