簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM