如何检查一个精确字符串是否存在于另一个字符串中?
我现在遇到了一点问题。我想写一个程序,能够在一个字符串中高亮显示某个单词或短语的出现,但前提是这个字符串必须完全相同。我遇到的麻烦是,如何判断我匹配的短语是否包含在另一个更大的短语中。
这里有个简单的例子来说明这个问题:
>>> indicators = ["therefore", "for", "since"]
>>> phrase = "... therefore, I conclude I am awesome."
>>> indicators_in_phrase = [indicator for indicator in indicators
if indicator in phrase.lower()]
>>> print indicators_in_phrase
['therefore', 'for']
我不想把'for'这个词包含在列表里。我知道它为什么会被包含,但我想不出有什么表达式可以把这样的子字符串过滤掉。
我注意到网站上有其他类似的问题,但每个问题都涉及到正则表达式(Regex),而我对这个还不太熟悉,尤其是在Python中。我想知道有没有什么简单的方法可以解决这个问题,而不使用正则表达式?如果没有的话,能否提供一个相应的正则表达式,以及它在上面例子中的实现方式,我会非常感激。
8 个回答
2
正则表达式是最简单的方法!
提示:
re.compile(r'\btherefore\b')
然后你可以更改中间的单词!
编辑:我为你写了这个:
import re
indicators = ["therefore", "for", "since"]
phrase = "... therefore, I conclude I am awesome. "
def find(phrase, indicators):
def _match(i):
return re.compile(r'\b%s\b' % (i)).search(phrase)
return [ind for ind in indicators if _match(ind)]
>>> find(phrase, indicators)
['therefore']
5
确实有一些方法可以不使用正则表达式来实现这个,但大多数方法都复杂得让你后悔没有花时间去学习简单的正则表达式。
2
这只需要一行代码就能用正则表达式解决...
import re
indicators = ["therefore", "for", "since"]
phrase = "... therefore, I conclude I am awesome."
indicators_in_phrase = set(re.findall(r'\b(%s)\b' % '|'.join(indicators), phrase.lower()))