Python:用prefixStringSuffix替换字符串保留原始大小写,但在搜索匹配时忽略大小写
题
所以我要做的是替换字符串<!> quot; keyword <!> quot;同
"<b>keyword</b>"
在更大的字符串中。
示例:
myString = <!>“HI那里。你应该为那份工作更高的那个人。嗨嗨。<!>“
keyword = <!> quot; hi <!> quot;
我想要的结果是:
result = "<b>HI</b> there. You should higher that person for the job.
<b>Hi</b> <b>hi</b>."
在用户输入关键字之前,我不知道关键字是什么 并且在查询运行之前不会知道语料库(myString)。
我找到了一个大部分时间都有效的解决方案,但有一些误报,
namely it would return "<b>hi<b/>gher"
这不是我想要的。还要注意我
我试图保留原始文本的大小写,并且匹配应该采取
不论案件如何。所以如果关键字是<!> quot; hi <!> quot;它应该取代
HI with <b>HI</b> and hi with <b>hi</b>.
我最接近的是使用稍微派生的版本: http://code.activestate.com/recipes/576715/ 但我仍然无法弄清楚如何进行第二次字符串传递来修复上面提到的所有误报。
或使用NLTK的WordPunctTokenizer(简化标点符号等一些内容) 但我不确定如果不这样做,我会如何将句子重新组合在一起 有一个反向函数,我想保留myString的原始标点符号。必要的是,对所有令牌进行连接并不会返回原始令牌 串。例如,我不想替换<!>“7 - 7 <!>”;用<!>“7-7 <!>”;如果原始文本具有<!>“7 - 7 <!>”,则将令牌重新组合为原始文本时。
希望足够清楚。看起来像一个简单的问题,但它的结果比我想象的要困难一些。
解决方案
这好吗?
>>> import re
>>> myString = "HI there. You should higher that person for the job. Hi hi."
>>> keyword = "hi"
>>> search = re.compile(r'\b(%s)\b' % keyword, re.I)
>>> search.sub('<b>\\1</b>', myString)
'<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>.'
其他提示
你应该可以使用re.sub
使用单词boundary assertion \b
来轻松地执行此操作,这只在单词边界匹配:
import re
def SurroundWith(text, keyword, before, after):
regex = re.compile(r'\b%s\b' % keyword, re.IGNORECASE)
return regex.sub(r'%s\0%s' % (before, after), text)
然后你得到:
>>> SurroundWith('HI there. You should hire that person for the job. '
... 'Hi hi.', 'hi', '<b>', '</b>')
'<b>HI</b> there. You should hire that person for the job. <b>Hi</b> <b>hi</b>.'
如果对于构成<!>“字边界的内容有更复杂的标准,<!> quot;你必须做类似的事情:
def SurroundWith2(text, keyword, before, after):
regex = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % keyword,
re.IGNORECASE)
return regex.sub(r'\1%s\2%s\3' % (before, after), text)
您可以修改[^a-zA-Z0-9]
群组以匹配您认为是<!>“非词的任何内容。<!>
我认为最好的解决方案是正则表达式......
import re
def reg(keyword, myString) :
regx = re.compile(r'\b(' + keyword + r')\b', re.IGNORECASE)
return regx.sub(r'<b>\1</b>', myString)
当然,您必须首先制作关键字<!>“正则表达式<!>”; (引用任何正则表达式特殊字符)。
这是来自挑剔委员会的一个建议。 : - )
myString = "HI there. You should higher that person for the job. Hi hi."
myString.replace('higher','hire')