我正在使用 Python v2.7,我想知道您是否可以判断一个单词是否在字符串中。
例如,如果我有一个字符串和我想查找的单词:
str = "ask and asked, ask are different ask. ask"
word = "ask"
我应该如何编码,以便我知道我获得的结果不包含属于其他单词的单词。在上面的例子中,除了“asked”之外,我想要所有的“ask”。
我已尝试使用以下代码,但它不起作用:
def exact_Match(str1, word):
match = re.findall(r"\\b" + word + "\\b",str1, re.I)
if len(match) > 0:
return True
return False
有人可以解释一下我该怎么做吗?
最佳答案
您可以使用以下功能:
>>> test_str = "ask and asked, ask are different ask. ask"
>>> word = "ask"
>>> def finder(s,w):
... return re.findall(r'\b{}\b'.format(w),s,re.U)
...
>>> finder(text_str,word)
['ask', 'ask', 'ask', 'ask']
请注意,您需要
\b
对于边界正则表达式!或者您可以使用以下函数返回 words 的索引:
在拆分字符串中:
>>> def finder(s,w):
... return [i for i,j in enumerate(re.findall(r'\b\w+\b',s,re.U)) if j==w]
...
>>> finder(test_str,word)
[0, 3, 6, 7]
关于regex - Python - 检查字符串是否在更大的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918227/