簡體   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