[英]match pattern to its counterpart from a list of patterns
In Python, I want to have a pair like this: 在Python中,我想要这样的一对:
patterns: 图案:
abc, def
ghi, jkl
mno, xyz
The idea is: given a string, I want to search for occurrence of any of the pattern p from patterns and when I find a match, I would like to subsititute it with its counterpart. 这个想法是:给定一个字符串,我想从模式中搜索任何模式p的出现,当我找到一个匹配项时,我想用它的对应项替换它。
For example: 例如:
this is an def
wer string (replaced string)
这是一个
def
WER串(replaced string)
lot of matches together abc-ghi-mno 很多比赛在一起abc-ghi-mno
def-jkl-xyz
(replaced string)
def-jkl-xyz
(replaced string)
Uptil now, I was replacing pattern matches with empty string and here is how I was doing this: 直到现在,我都用空字符串替换了模式匹配,这就是我的操作方式:
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)
So, how can i substitute for a pair of strings here ? 那么,我如何在这里代替一对琴弦? What is the
pythonic
way of doing this ? 这样做的
pythonic
方式是什么?
You can support overlapping strings by using the function-accepting version of re.sub
: 您可以使用
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
Is that what you're looking for? 那是您要找的东西吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.