簡體   English   中英

如何使用re.sub實際替換文件名?

[英]How can I use re.sub to actually replace the filenames?

我將使用Mac程序Patterns的正則表達式放在一起,當我在python腳本中使用代碼時,無法獲得對文件名所做的更改。 我知道您需要將re.sub的輸出分配給新字符串,這是一個常見錯誤。 我做到了,但仍然無法獲得正確的結果。

這是給定文件名作為輸入的我的代碼:

real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe

real time with bill maher 2014 01 24 hdtv x264-2hd.mp4

Real Time With Bill Maher 2014.02.07.hdtv.x264-2hd.mp4

import re
import os

path = "/Users/USERNAME/Movies"
pattern = "(real[. ]time[. ]with[. ]bill[. ]maher[. ])"
replacement = "Real Time with Bill Maher "

def renamer(path, pattern, replacement):
    for dirpath,_,file in os.walk(path):
        for oldname in file:
            if re.search(pattern, oldname, re.I):
                newname = re.sub(pattern, replacement, oldname)
                newpath = os.path.join(dirpath, newname)
                oldpath = dirpath + "/" + oldname
                print newpath + " < new"
                print oldpath
                os.rename(oldpath, newpath)

renamer(path, pattern, replacement)

該代碼缺少re.sub調用中的re.I標志:

>>> pattern = "(real[. ]time[. ]with[. ]bill[. ]maher[. ])"
>>> replacement = "Real Time with Bill Maher "
>>> re.sub(pattern, replacement, 'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe')
'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe'
>>> re.sub(pattern, replacement, 'real.time.With.bill.maher.JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe', flags=re.I)
'Real Time with Bill Maher JUST.OVERTIME.2014.01.31.WEB-DL.Shadoe'

您應將flags指定為關鍵字參數,否則將被識別為count (替換計數)參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM