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

2024-06-26 13:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题以前已经有人回答过了,但我的问题有点不同。在

我想要的是在文本中搜索特定的关键字,并用<b></b>来代替它们。下面一个例子解释了四种不同的可能性:

关键字

输入句

预期输出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'--(只替换以关键字开头的匹配单词。注意,即使匹配部分,整个单词也会被替换)

被匹配的任何单词替换

任何一个匹配的单词都不应被的输出替换。匹配词的大小写保持不变

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

但这并不能使找到的单词保持完整。在


Tags: andtorehelloisplace关键字单词
1条回答
网友
1楼 · 发布于 2024-06-26 13:12:44
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)

输出:

^{pr2}$

相关问题 更多 >