繁体   English   中英

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

[英]Python Search word contains : in a string

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

知道搜索必须是精确的例子:我搜索单词'for'当句子包含单词'formatted'时它必须返回 me not exist 。

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包装转义模式的单词边界。 相反,我们积极向前看以确保单词后有空格或字符串结尾。 最后,我们只捕获单词。

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 匹配空字符串,但仅在单词的开头或结尾。单词被定义为单词字符的序列。”。 在: 和空格之间没有单词边界,因为它们都不是单词字符序列的一部分。

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

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:'会发生什么。 这里我们没有单词边界,也没有空格。 我们必须在文本末尾添加一个检查给我们:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM