检查单词是否在字符串中出错

2024-06-28 19:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python - Check If Word Is In A String中的以下内容

>>> def findWholeWord(w):
...     return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
... 
>>> findWholeWord('seek')('those who seek shall find')  
<_sre.SRE_Match object at 0x22c1828>
>>> findWholeWord('seek') 
<built-in method search of _sre.SRE_Pattern object at 0x22b8190>
>>> findWholeWord('seek')('those who seek shall find')  
<_sre.SRE_Match object at 0x22c1828>
>>> findWholeWord('seek')('those who shall find') 

这是错误还是结果?在

^{pr2}$

Tags: researchifobjectcheckmatchseekfind
2条回答

这是一段有趣的代码,但在python中,在字符串中查找单词实际上要简单得多。这甚至不需要函数:

 if some_word in some_str.split():
      ....

要只查找子字符串而不是整个单词,请省略split部分:

^{pr2}$

匹配对象就是结果,从中可以访问更多函数,比如

['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__format__'
, '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__','end', 'endpos'
, 'expand', 'group', 'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're'
, 'regs', 'span', 'start', 'string']

因此,对于返回的对象,您可以例如执行.span()来获取所查找单词的开始和结束索引。在

相关问题 更多 >