在Python中,我希望有这样一对:
模式:
abc, def
ghi, jkl
mno, xyz
这个想法是:给定一个字符串,我想从模式中搜索任何模式p的出现,当我找到匹配时,我想用它的对应物替换它。
例如:
这是一个def
字符串(replaced string)
很多比赛abc-ghi-mno
def-jkl-xyz
(replaced string)
现在升级,我用空字符串替换模式匹配,这就是我这样做的方式:
regExps = [ re.compile(re.escape(p), re.IGNORECASE) for p in patterns ]
def cleanseName(dirName, name):
# please ignore dirName here since I have just put here a snippet of the code
old = name
new = ""
for regExp in regExps:
if regExp.search(old):
new = regExp.sub("", old).strip()
old = new
if new != "":
new = old
print("replaced string: %s" % new)
那么,我怎么能在这里替换一对字符串呢? pythonic
这样做的方式是什么?
答案 0 :(得分:2)
您可以使用功能接受版re.sub
:
import re
substitutions = {
"abc": "def",
"def": "ghi",
"ghi": "jkl",
"jkl": "mno",
"mno": "pqr"
}
def match_to_substitution(match):
return substitutions[match.group()]
string = "abc def ghi jkl mno"
substitute_finder = re.compile("|".join(map(re.escape, substitutions)))
substitute_finder.sub(match_to_substitution, string)
#>>> 'def ghi jkl mno pqr'
答案 1 :(得分:0)
patterns = [('abc','def'),('ghi','jkl'),('mno','xyz')]
def cleanse_name(name, patterns):
for from_,to in patterns:
name = re.sub(re.escape(from_), to, name, flags=re.I)
print(name)
cleanse_name("abcghimno Smith", patterns)
# defjklxyz Smith
这就是你要找的东西吗?