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

问题描述 投票:2回答:1

我想替换文本行中所有出现的一组字符串。我想出了这种方法,但是我确信有更好的方法可以做到这一点:

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
python regex case-insensitive
1个回答
4
投票

尝试

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

© www.soinside.com 2019 - 2024. All rights reserved.