加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 找到字符串的完全匹配

发布时间:2020-12-20 11:27:39 所属栏目:Python 来源:网络整理
导读:我使用以下函数来查找字符串中单词的完全匹配. def exact_Match(str1,word): result = re.findall('b'+word+'b',str1,flags=re.IGNORECASE) if len(result)0: return True else: return Falseexact_Match(str1,word) 但是,如果只是因为以下字符串获奖,我
我使用以下函数来查找字符串中单词的完全匹配.

def exact_Match(str1,word):
    result = re.findall('b'+word+'b',str1,flags=re.IGNORECASE)
    if len(result)>0:
        return True
    else:
        return False

exact_Match(str1,word)

但是,如果只是因为以下字符串获奖,我会得到“奖励”和“获奖”这两个词的完全匹配.

str1 = "award-winning blueberries"
word1 = "award"
word2 = "award-winning"

我如何才能得到它,以便re.findall将整个单词与连字符和其他标点符号相匹配?

解决方法

制作自己的单词边界:

def exact_Match(phrase,word):
    b = r'(s|^|$)' 
    res = re.match(b + word + b,phrase,flags=re.IGNORECASE)
    return bool(res)

从这里复制粘贴到我的翻译:

>>> str1 = "award-winning blueberries"
>>> word1 = "award"
>>> word2 = "award-winning"
>>> exact_Match(str1,word1)
False
>>> exact_Match(str1,word2)
True

实际上,铸造到bool是不必要的,根本没有帮助.没有它,功能会更好:

def exact_Match(phrase,word):
    b = r'(s|^|$)' 
    return re.match(b + word + b,flags=re.IGNORECASE)

注意:exact_Match是非常规的套管.只需将其称为exact_match.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读