gpt4 book ai didi

python - 多个正则表达式替换

转载 作者:太空宇宙 更新时间:2023-11-04 01:11:05 24 4
gpt4 key购买 nike

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

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

关于python - 多个正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27616044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com