在字符串中查找单个或多个单词

时间:2014-06-14 18:18:54

标签: python string

我正在尝试编写一个脚本,该脚本将在给定字符串中找到单个单词或由多个单个单词组成的字符串。我发现this answer看起来很像我需要的东西,但我真的不明白它是如何工作的。

使用上述答案中提供的代码,我有:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

st1 = 'those who seek shall find'
st2 = 'swordsmith'

print findWholeWord('seek')(st1)          # -> <match object>
print findWholeWord('these')(st1)         # -> None
print findWholeWord('THOSE')(st1)         # -> <match object>
print findWholeWord('seek shall')(st1)    # -> <match object>
print findWholeWord('word')(st2)          # -> None

此函数返回类似<_sre.SRE_Match object at 0x94393e0>(当找到单词时)或None(当它们不是时),我希望函数返回True如果找到或不找到单词,则分别为1}}或False。 由于我不清楚这个函数是如何工作的,我不确定我是怎么做的。

我从未见过一个函数被调用传递两个变量(?),即:findWholeWord(word)(string),这是做什么的?

2 个答案:

答案 0 :(得分:1)

re是正则表达式模块。 findWholeWord创建一个正则表达式对象,该对象将与您传递的单词(模式)匹配。 findWholeWord返回一个函数;正则表达式对象的搜索方法 - 注意缺少&#39;()&#39;在退货声明的最后。

import re
def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

>>> search = findWholeWord('seek')
>>> print search
<built-in method search of _sre.SRE_Pattern object at 0x032F70A8>
>>>
如果找到模式,

re.search将返回匹配对象,如果不是,则返回None。匹配对象评估为True。

>>> search = findWholeWord('seek')
>>> print search
<built-in method search of _sre.SRE_Pattern object at 0x032F70A8>
>>> 
>>> match = search('this string contains seek')
>>> print match, bool(match)
<_sre.SRE_Match object at 0x032FDC20> True
>>> match = search('this string does not contain the word you are looking for')
>>> print match, bool(match)
None False
>>>

在您的示例中,findWholeWord('seek')(st1)正在调用与`seek&#39;匹配的正则表达式的搜索方法。并传递字符串st1

>>> st1 = 'those who seek shall find'
>>> match = search(st1)
>>> print match, bool(match)
<_sre.SRE_Match object at 0x032FDC20> True
>>> match = findWholeWord('seek')(st1)
>>> print match, bool(match)
<_sre.SRE_Match object at 0x032FDC60> True
>>> 

答案 1 :(得分:0)

if findWholeWord('seek')(st1) == None:
    return False
else:
    return True

或者:

if findWholeWord('seek')(st1): #this is evaluated 'True'
        #do something
else:
        #there is no search match, do something else

或者:

import re

def findWholeWord(w, string):
    pattern = re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE)
    if pattern.search(string):
        return True
    else:
        return False
相关问题