我可以在不区分大小写的方法中使用以下解决方案替换字符串内容中的单词
http://code.activestate.com/recipes/552726/
import re
class str_cir(str):
''' A string with a built-in case-insensitive replacement method '''
def ireplace(self,old,new,count=0):
''' Behaves like S.replace(), but does so in a case-insensitive
fashion. '''
pattern = re.compile(re.escape(old),re.I)
return re.sub(pattern,new,self,count)
我的问题是我需要准确替换我提供的单词
para = "Train toy tram dog cat cow plane TOY Joy JoyTOY"
我需要用“火腿”替换“玩具”这个词,我明白了
'Train HAM tram dog cat cow plane HAM Joy JoyHAM'
我需要的是
'Train HAM tram dog cat cow plane HAM Joy JoyTOY'
请您参考如下方法:
在关键字的开头和结尾添加\b:
pattern = re.compile("\\b" + re.escape(old) + "\\b",re.I)
\b表示词边界,匹配词首尾的空字符串(由字母数字或下划线字符序列定义)。 ( Reference )
正如@Tim Pietzcker 指出的那样,如果关键字中有非单词(不是字母数字和下划线)字符,它就不会像您想象的那样工作。
