在不区分大小写的方法中,我可以使用以下解决方案替换字符串内容中的单词
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'发布于 2012-06-26 19:01:26
在关键字的开头和结尾添加\b:
pattern = re.compile("\\b" + re.escape(old) + "\\b",re.I)\b表示单词边界,它匹配单词开头和结尾的空字符串(由字母数字或下划线字符序列定义)。(Reference)
正如@Tim Pietzcker指出的那样,如果关键字中有非单词(不是字母数字,也不是下划线)字符,它将不会像你想象的那样工作。
发布于 2012-06-26 19:00:11
将\b放在正则表达式的开头和结尾。
发布于 2012-06-26 19:00:20
使用单词边界(\b)对正则表达式中要使用的单词进行换行。
https://stackoverflow.com/questions/11205844
复制相似问题