[英]match pattern to its counterpart from a list of patterns
在Python中,我想要這樣的一對:
圖案:
abc, def
ghi, jkl
mno, xyz
這個想法是:給定一個字符串,我想從模式中搜索任何模式p的出現,當我找到一個匹配項時,我想用它的對應項替換它。
例如:
這是一個def
WER串(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
方式是什么?
您可以使用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'
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
那是您要找的東西嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.