【发布时间】: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 字典弄乱了序列。