我整理了一个使用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)
答案 0 :(得分:2)
代码在re.I
调用中缺少re.sub
标记:
>>> 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
(替换计数)参数。