使用 python 中的字符串输入数组重写多个附加替换方法的更好方法?

A better way to rewrite multiple appended replace methods using an input array of strings in python?

我有一个非常丑陋的命令,我使用许多附加的 "replace()" 方法来 replace/substitute/scrub 来自原始字符串的许多不同字符串。例如:

newString = originalString.replace(' ', '').replace("\n", '').replace('()', '').replace('(Deployed)', '').replace('(BeingAssembled)', '').replace('ilo_', '').replace('ip_', '').replace('_ilop', '').replace('_ip', '').replace('backupnetwork', '').replace('_ilo', '').replace('prod-', '').replace('ilo-','').replace('(EndofLife)', '').replace('lctcvp0033-dup,', '').replace('newx-', '').replace('-ilo', '').replace('-prod', '').replace('na,', '')

如您所见,这是一个非常丑陋的语句,并且很难知道长命令中包含哪些字符串。这也使得重用变得困难。

我想做的是定义一个包含许多替换对的输入数组,其中替换对看起来像 [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>];更大的数组看起来像:

replacementArray = [
                     [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
                     [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
                     [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>],
                     [<ORIGINAL_SUBSTRING>, <NEW_SUBSTRING>]
]

AND,我想将该 replacementArray 连同需要擦除的原始字符串传递给具有类似结构的函数:

def replaceAllSubStrings(originalString, replacementArray):
    newString = ''
    for each pair in replacementArray:
        perform the substitution
    return newString

我的问题是: 编写函数代码块以应用 replacementArray 中的每一对的正确方法是什么?我应该使用 "replace()" 方法吗? "sub()" 方法?我对如何将原始代码重组为一个漂亮干净的函数感到困惑。

提前感谢您提供的任何帮助。

你的想法是对的。使用序列解包迭代每对值:

def replaceAllSubStrings(originalString, replacementArray):
    for in_rep, out_rep in replacementArray:
        originalString = originalString.replace(in_rep, out_rep)
    return originalString

使用re怎么样?

import re

def make_xlat(*args, **kwds):  
    adict = dict(*args, **kwds)  
    rx = re.compile('|'.join(map(re.escape, adict)))  
    def one_xlat(match):  
        return adict[match.group(0)]  
    def xlat(text):  
        return rx.sub(one_xlat, text)  
    return xlat

replaces = {
    "a": "b",
    "well": "hello"
}

replacer = make_xlat(replaces)
replacer("a well?")
# b hello?

您可以在 replaces 中添加任意数量的项目。