繁体   English   中英

从模式列表中将模式与其对应项进行匹配

[英]match pattern to its counterpart from a list of patterns

在Python中,我想要这样的一对:

图案:

abc, def
ghi, jkl
mno, xyz

这个想法是:给定一个字符串,我想从模式中搜索任何模式p的出现,当我找到一个匹配项时,我想用它的对应项替换它。

例如:

  • 这是一个abcwer字符串
  • 这是一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM