Skip to main content
 首页 » 编程设计

不区分大小写的 Python 查找并替换为找到的相同单词

2024年10月24日12lautakyan007

我知道这个问题之前已经在这里回答过Case insensitive replace但我的有点不同。

我想要的是在文本中搜索某些关键字并用 <b> 包围它们来替换它们和 </b> .通过以下示例解释了四种不同的可能性:

关键字 = ['hell', 'world']

输入句子 = '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>' -- (任何出现的 hell 都被替换,但被完整的匹配词替换)

预期输出 4 = '<b>Hell</b> is a wonderful place to say <b>hell</b>o and sell s<b>hell</b>s' -- (任何出现的 hell 都会被替换,但不会被完整的匹配词替换。匹配词的大小写保持不变)

链接的 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