[英]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.