我知道这个问题以前已经有人回答过了,但我的问题有点不同。在
我想要的是在文本中搜索特定的关键字,并用<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'
但这并不能使找到的单词保持完整。在
输出:
^{pr2}$相关问题 更多 >
编程相关推荐