Skip to main content
 首页 » 编程设计

python之多个 Re.Subs Python

2025年05月04日10unruledboy

抱歉,我无法从 Python 文档或我从 Google 找到的任何资料中弄清楚这一点。

因此,我一直致力于重命名文件,其中 99% 的代码来自 StackOverflow 的一位出色助手。

我正在整理一个重命名脚本(这是我从这里的某人那里得到的帮助)与名称(而不是扩展名)一起工作的。

我确定我会想出更多的替代品,但我现在的问题是我不知道如何做不止一个 re.sub。 当前代码(用空格替换点):

import os, shutil, re 
 
def rename_file (original_filename): 
    name, extension = os.path.splitext(original_filename) 
    #Remove Spare Dots 
    modified_name = re.sub("\.", r" ", name) 
    new_filename = modified_name + extension 
    try: 
        # moves files or directories (recursively) 
        shutil.move(original_filename, new_filename) 
    except shutil.Error: 
        print ("Couldn't rename file %(original_filename)s!" % locals()) 
[rename_file(f) for f in os.listdir('.') if not f.startswith('.')] 

希望也能

re.sub("C126", "Perception", name) 
re.sub("Geo1", "Geography", name) 

此外,如果我能让它把除“and|if”以外的任何单词的首字母大写,那就太棒了

我试过了

modified_name = re.sub("\.", r" ", name) && re.sub(...  

但这没有用;也没有将它们放在不同的线路上。我如何做我想做/做的所有潜艇和东西?

请您参考如下方法:

只需一遍又一遍地操作同一个字符串,每次都替换它:

name = re.sub(r"\.", r" ", name) 
name = re.sub(r"C126", "Perception", name) 
name = re.sub(r"Geo1", "Geography", name) 

不过@DanielRoseman 是对的,这些是文字模式,不需要描述/找到/替换正则表达式。您可以使用 timeit 来证明普通的旧 replace() 是可取的:

In [16]: timeit.timeit("test.replace('asdf','0000')",setup="test='asdfASDF1234'*10") 
Out[16]: 1.0641241073608398 
 
In [17]: timeit.timeit("re.sub(r'asdf','0000',test)",setup="import re; test='asdfASDF1234'*10") 
Out[17]: 6.126996994018555