Skip to main content
 首页 » 编程设计

python之多个正则表达式替换

2024年08月26日30del

我正在使用以下代码规范化文件名:

new_file = re.sub('[. ]', '_', old_file.lower()) 
new_file = re.sub('__+', '_', new_file) 
new_file = re.sub('[][)(}{]',  '', new_file) 
new_file = re.sub('[-_]([^-_]+)$',  r'.\1', new_file) 

我的问题是有没有可能以更好的方式编写这段代码?

我找到了 following example :

def multiple_replace(dict, text): 
    # Create a regular expression  from the dictionary keys 
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) 
 
    # For each match, look-up corresponding value in dictionary 
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)  
 
dict = { 
    "Larry Wall" : "Guido van Rossum", 
    "creator" : "Benevolent Dictator for Life", 
    "Perl" : "Python", 
}  

但此代码仅适用于普通字符串。第 3 行中的 map(re.escape, ... “破坏”了正则表达式。

问候,
雷

请您参考如下方法:

如果您只是在寻找更易于维护和更少重复的代码(而不是算法更改),请使用简单的 for 循环:

SUBS = [ 
  ('[. ]', '_'), 
  ('__+', '_'), 
  ('[][)(}{]',  ''), 
  ('[-_]([^-_]+)$',  r'.\1'), 
] 
 
def normalize(name): 
    name = name.lower() 
    for pattern, replacement in SUBS: 
        name = re.sub(pattern, replacement, name) 
    return name