Python 搜索词包含 : 在一个字符串中

Python Search word contains : in a string

我尝试研究某个单词是否存在于字符串中。搜索词包含字符':'的问题。即使我使用了转义,搜索也没有成功。 在示例中,搜索词 'decision :' return 不存在,而句子中确实存在该词。

知道搜索必须是精确的示例:我搜索单词 'for' 它必须 return 当句子包含单词 'formatted'.

时,我不存在
import re
texte ="  hello \n a formated test text   \n decision :   repair \n toto \n titi"
word_list = ['decision :', 'for']
def verif_exist (word_list, paragraph):
   
    exist = False
    for word in word_list:
        exp = re.escape(word)
      
        print(exp)
        if re.search(r"\b%s\b" % exp, paragraph, re.IGNORECASE):
            print("From exist, word detected: " + word)
            exist = True
        if exist == True:
            break
    return exist
if verif_exist(word_list, texte):
    print("exist")
else:
    print("not exist") ```

唯一需要的更改是删除第二个 \b 用于包裹转义模式的单词边界。相反,我们积极向前看,以确保单词后有一个 space 或字符串结尾。最后,我们只捕获单词。

import re
texte ="  hello \n a formated test text   \n decision :   repair \n toto \n titi"
word_list = ['decision :', 'for']
def verif_exist (word_list, paragraph):
    for word in word_list:
        exp = re.escape(word)
      
        print(exp)
        if re.search(r"\b(%s)(?=\s|$)" % exp, paragraph, re.IGNORECASE): # remove second word boundary, as we want to match non word characters after the word (space and colon)
            print("From exist, word detected: " + word)
            return True

    return False
if verif_exist(word_list, texte):
    print("exist")
else:
    print("not exist")

文档指出:“\b 匹配空字符串,但仅在单词的开头或结尾。单词定义为单词字符的序列。”。 : 和 space 之间没有单词边界,因为两者都不属于单词字符序列。

也许您可以在正则表达式中使用单词边界或白色space。

import re

texte = "  hello \n a formated test text   \n decision :   repair \n toto \n titi"
word_list = ['decision :', 'for']


def verif_exist(word_list, paragraph):
    for word in word_list:
        exp = re.escape(word)
        print(exp)
        if re.search(fr"\b{exp}(\b|\s)", paragraph, re.IGNORECASE):
            print("From exist, word detected: " + word)
            return True
    return False


if verif_exist(word_list, texte):
    print("exist")
else:
    print("not exist")

这还不够完美。您可能需要考虑如果您的文本只是 'decision :' 会发生什么。这里我们没有单词边界,也没有 whitespace。我们必须在文本末尾添加一个检查给我们:

    if re.search(fr"\b{exp}(\b|\s|$)", paragraph, re.IGNORECASE):

现在您可能必须在正则表达式的开头做一些类似于单词边界的事情。