python - 有没有办法在我的搜索和替换代码中构建异常?

标签 python

我需要从文件名中删除下划线,但不是所有下划线。

原始文件:“Bob's_House_RZ.png”、“Jim_and_Judy's_House_RR.png”

期望结果:“Bob's House_RZ.png”、“Jim and Judy's_House_RR.png”

我已经编写了一些代码来替换字符,但我想知道如何为某些模式添加异常(exception),例如上面的“_RR”和“_RZ”。由于我是编程新手,我想知道最佳实践是什么。感谢您的帮助。

import os

target_dir = r"C:\Somefolder\\"

old_string = "_"
new_string = " "

extension = ".png"
count = 0


for file in os.listdir(target_dir):
    if file.endswith(extension):
        if file.find(old_string) > 0:
            count += 1
            os.rename(target_dir + "\\" + file, target_dir + "\\" + file.replace(old_string, new_string))

最佳答案

使用短正则表达式模式:

import re

extension = ".png"

# for demonstration purpose
files = ["Bob's_House_RZ.png", "Jim_and_Judy's_House_RR.png"]
pat = re.compile(r'_(?!(R[RZ]\b))')

for f in files:
    if f.endswith(extension):
        new_fname = pat.sub(' ', f)
        print(new_fname)
        # do the renaming logic

输出:

Bob's House_RZ.png
Jim and Judy's House_RR.png

关于python - 有没有办法在我的搜索和替换代码中构建异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57012828/

相关文章:

python - 如何匹配模式并向其添加字符

python - 如何前瞻性地使用 Pandas rolling_* 函数

python - 沿 2 个轴的 numpy `take`

python - boto 模块的 list() 方法中的问题

python - 从字典 python 中创建所有可能的句子

python - Windows 上的 Tensorflow for Poets(重新训练 Inception)

python - 带子图的猫图有限制吗?

python - Groupby 序列计数和序列持续时间

python - 索引错误 : list index out of range (Python)

python - Pandas/Python 中的分块、处理和合并数据集