【发布时间】:2015-06-24 09:26:48
【问题描述】:
我知道这个问题在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>' --(任何出现的地狱都被替换,但被完整的匹配词替换)
预期输出 4 = '<b>Hell</b> is a wonderful place to say <b>hell</b>o and sell s<b>hell</b>s' -- (任何出现的地狱都会被替换,但不会被完整的匹配词替换。匹配词的大小写保持原样)
链接的 SO 问题将单词替换为 found 关键字,这不是我想要的。我想保持输入句子的大小写不变。有人可以帮我找到上述四种情况的解决方案吗?
我试过的代码:
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'
但这并不能保持找到的单词完好无损。
【问题讨论】:
-
你的预期输出是什么?
-
给定输入句子和关键字列表,这四种翻译文本是预期的输出
-
一个输入句子需要四个?你必须展示你的尝试..
-
@AvinashRaj 我正在使用链接的 SO 帖子中讨论的方法。
-
看起来关键字应该是“地狱”,而不是你好;)