[英]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.