Python 不区分大小写替换所有多个字符串

Python Case Insensitive Replace All of multiple strings

我想替换文本行中所有出现的一组字符串。我想到了这种方法,但我相信还有更好的方法:

myDict = {}
test = re.compile(re.escape('pig'), re.IGNORECASE)
myDict['car'] = test
test = re.compile(re.escape('horse'), re.IGNORECASE)
myDict['airplane'] = test
test = re.compile(re.escape('cow'), re.IGNORECASE)
myDict['bus'] = test

mystring = 'I have this Pig and that pig with a hOrse and coW'

for key in myDict:      
    regex_obj = myDict[key]
    mystring = regex_obj.sub(key, mystring)

print mystring

我有这辆车和那辆车,还有飞机和公共汽车

根据下面@Paul Rooney 的回答,理想情况下我会这样做:

def init_regex():
    rd = {'pig': 'car', 'horse':'airplane', 'cow':'bus'}
    myDict = {}
    for key,value in rd.iteritems():
        pattern = re.compile(re.escape(key), re.IGNORECASE)
        myDict[value] = pattern

    return myDict

def strrep(mystring, patternDict):
    for key in patternDict:
        regex_obj = patternDict[key]
        mystring = regex_obj.sub(key, mystring)

    return mystring

尝试

import itertools
import re

mystring = 'I have this Pig and that pig with a hOrse and coW'

rd = {'pig': 'car', 'horse':'airplane', 'cow':'bus'}

cachedict = {}

def strrep(orig, repdict):
    for k,v in repdict.iteritems():
        if k in cachedict:
            pattern = cachedict[k]
        else:
            pattern = re.compile(k, re.IGNORECASE)
            cachedict[k] = pattern
        orig = pattern.sub(v, orig)
    return orig

print strrep(mystring, rd)

此答案最初是为 python2 编写的,但对于 python 3,您将使用 repdict.items 而不是 repdict.iteritems