簡體   English   中英

Python 不區分大小寫查找並替換為相同的找到的單詞

[英]Python case insensitive find and replace with the same found word

我知道這里之前已經回答了這個問題不區分大小寫的替換,但我的有點不同。

我想要的是在文本中搜索某些關鍵字,並用<b></b>它們包圍起來。 通過下面的示例解釋了四種不同的可能性:

關鍵字= ['hell', 'world']

Input Sentence = 'Hell is a wonderful place to say hello and sell shells'

預期輸出 1 = '<b>Hell</b> is a wonderful place to say hello and sell shells' --(沒有替換為關鍵字 'hell' 而是找到的詞 'Hell'。僅替換了完整匹配。

預期輸出 2 = '<b>Hell</b> is a wonderful place to say <b>hello</b> and sell shells' -- (僅替換以關鍵字開頭的匹配詞。注意整個詞即使匹配是部分的,也會被替換

預期輸出 3 = '<b>Hell</b> is a wonderful place to say <b>hello</b> and sell <b>shells</b>' -- (任何出現的地獄都會被替換完全匹配詞)

預期輸出 4 = '<b>Hell</b> is a wonderful place to say <b>hell</b>o and sell s<b>hell</b>s' -- (任何出現的地獄都被替換但不是通過完整的匹配詞。匹配詞的大小寫保持不變

鏈接的 SO 問題,用找到的關鍵字替換了這個詞,這不是我想要的。 我想保持輸入句子的大小寫完整。 有人可以幫我找到以上四種情況的解決方案嗎?

我試過的代碼:

import re
insensitive_hippo = re.compile(re.escape('hell'), re.IGNORECASE)
insensitive_hippo.sub('hell', 'Hell is a wonderful place to say hello and sell shells')
'hell is a wonderful place to say hello and sell shells'

但這並不能保持找到的單詞完整無缺。

print re.sub(r"\b(hell)\b",r"<b>\1</b>",x,flags=re.I)

print re.sub(r"\b(hell\S*)",r"<b>\1</b>",x,flags=re.I)

print re.sub(r"\b(\S*hell\S*)",r"<b>\1</b>",x,flags=re.I)

print re.sub(r"(hell)",r"<b>\1</b>",x,flags=re.I)

輸出:

<b>Hell</b> is a wonderful place to say hello and sell shells
<b>Hell</b> is a wonderful place to say <b>hello</b> and sell shells
<b>Hell</b> is a wonderful place to say <b>hello</b> and sell <b>shells</b>
<b>Hell</b> is a wonderful place to say <b>hell</b>o and sell s<b>hell</b>s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM