【问题标题】:batch search and replace strings in filenames with python用python批量搜索和替换文件名中的字符串
【发布时间】:2011-12-13 09:21:14
【问题描述】:

我正在尝试编写一个小的 python 脚本来通过搜索和替换来重命名一堆文件名。例如:

原始文件名: MyMusic.Songname.Artist-mp3.iTunes.mp3

意向结果: 歌曲名.Artist.mp3

到目前为止我得到的是:

#!/usr/bin/env python
from os import rename, listdir

mustgo = "MyMusic."
filenames = listdir('.')

for fname in fnames:
  if fname.startswith(mustgo):
    rename(fname, fname.replace(mustgo, '', 1))

(据我所知是从这个网站得到的)

无论如何,这只会删除开头的字符串,而不是文件名中的那些。

我还想使用一个单独的文件(例如 badwords.txt),其中包含所有应该搜索和替换的字符串,这样我就可以更新它们而无需编辑整个代码。

Content of badwords.txt
MyMusic.
-mp3
-MP3
.iTunes
.itunes

我已经搜索了很长时间,但没有找到任何东西。非常感谢任何帮助!

谢谢!

【问题讨论】:

  • 对于一些小而脏的脚本来更改文件名 Perl 工作得更好,特别是由于强大的 RegEx 支持和易于运行的系统命令。

标签: python linux filenames rename


【解决方案1】:
import fnmatch
import re    
import os

with open('badwords.txt','r') as f:
    pat='|'.join(fnmatch.translate(badword)[:-1] for badword in 
                 f.read().splitlines())   

for fname in os.listdir('.'):
    new_fname=re.sub(pat,'',fname)
    if fname != new_fname:
        print('{o} --> {n}'.format(o=fname,n=new_fname))
        os.rename(fname, new_fname)

# MyMusic.Songname.Artist-mp3.iTunes.mp3 --> Songname.Artist.mp3
  • 请注意,某些文件可能会被覆盖(因此 丢失)如果两个名字在 badwords 已被删除。可以保留一组新的 fname,并且 在调用os.rename 之前检查以防止通过 名称冲突。
  • fnmatch.translate 采用 shell 样式模式并返回 等价的正则表达式。上面用来转换badwords (例如'.iTunes')转换成正则表达式(例如r'\.iTunes')。
  • 您的坏词列表似乎表明您想忽略大小写。你 可以通过在pat 的开头添加'(?i)' 来忽略大小写:

    with open('badwords.txt','r') as f:
       pat='(?i)'+'|'.join(fnmatch.translate(badword)[:-1] for badword in 
                           f.read().splitlines())
    

【讨论】:

  • 感谢您的快速回复!文件被覆盖应该没有任何问题。尽管我的 badwords 文件似乎表明我想忽略大小写,但事实并非如此。但我确实有以下问题:`文件“/usr/lib/python2.7/re.py”,第 244 行,在 _compile 中引发错误,v # invalid expression sre_constants.error: unknown extension`
  • 并使用 python 3 运行它,我得到:文件“/usr/lib/python3.2/sre_parse.py”,第 653 行,在 _parse 中引发错误(“未知扩展名”) sre_constants.error:未知扩展名
  • 你控制badwords.txt的内容吗?如果是这样,我会直接在那里编写正则表达式,并避免使用fnmatch.translate。代码会更简单,直接使用正则表达式可以实现更通用的模式匹配。
  • 您遇到的错误可能是由于 badwords.txt 中的模式未正确转换为正则表达式。请发布 badwords.txt 的内容。
  • 摆脱 fnmatch.translate 似乎可以解决问题!太好了谢谢!不过现在必须完善我的正则表达式 :) 无论如何,这是我的 badwords.txt 内容: Made-4-me.com_ .itunes .HDTV .hdtv -HDTV -hdtv .xvid .3vid -MUSIC
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 2010-11-14
  • 2021-09-23
  • 2020-05-12
  • 2015-11-13
相关资源
最近更新 更多