不了解python中的re.search

时间:2018-07-18 18:32:34

标签: python

我已经实现了这个简单的功能,以便搜索句子中的特定单词:

import re
def word_in_text(word, sentence):
    word = word.lower()
    sentence = sentence.lower()
    match = re.search(word, sentence)
    if match:
        return True
    return False

但这不适用于全世界。例如在句子中:

a = "RT @Kaus_Pandey17: Wrote some words about new #Liverpool"

我得到了这个奇怪的结果:

word_in_text('wrote',a)
False
word_in_text('Wrote',a)
False
word_in_text('some',a)
True
word_in_text('#Liverpool',a)
False
word_in_text('17',a)
True
word_in_text('Pandey',a)
False
word_in_text('RT',a)
False
word_in_text('some',a)
True

有一些不正确的False返回,我不明白为什么

谢谢

1 个答案:

答案 0 :(得分:-2)

您的变量不能与参数具有相同的名称。将变量名称更改为唯一的名称,如下所示:

import re

def word_in_text(word, sentence):
    wo = word.lower()
    sen = sentence.lower()
    match = re.search(wo, sen)
    if match:
        return True
    return False

print(word_in_text('Liverpl','RT @Kaus_Pandey17: Wrote some words about new #Liverpool'))