【问题标题】:Multiple regex substitutions多个正则表达式替换
【发布时间】:2015-02-21 08:10:32
【问题描述】:

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

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, ...“破坏”了正则表达式。

问候,
雷

【问题讨论】:

  • 您是否尝试过简单地删除re.escape,即将违规行更改为regex = re.compile("(%s)" % "|".join(dict))?我没有尝试过,但我看不出它为什么不起作用。
  • 我已经试过了。在这种情况下,第 5 行有一个错误。此外,在我的示例中,序列很重要,我发现 a 字典弄乱了序列。

标签: python regex


【解决方案1】:

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

SUBS = [
  ('[. ]', '_'),
  ('__+', '_'),
  ('[][)(}{]',  ''),
  ('[-_]([^-_]+)$',  r'.\1'),
]

def normalize(name):
    name = name.lower()
    for pattern, replacement in SUBS:
        name = re.sub(pattern, replacement, name)
    return name

【讨论】:

  • 我会鼓励 OP 将 ('[. ]', '_') 和 ('__+', '_') 合并到 ('[. _]+', '_') 中,这实际上是相同的,而不会变成一个非常不可读的正则表达式。
  • @user4815162342:感谢您的解决方案。我喜欢它,我会在我的代码中使用它...
猜你喜欢
  • 2012-02-16
  • 2012-10-15
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多