Take the 2-minute tour ×

I know there's a better way to do this, but I don't know what it is. I'm sorting through a list of files, and I would like to remove 'the usual suspects' so I can compare one list to another.

From what I understand, name.replace() look at each and every item in the listToClean for the phrases I picked, and replace them if present. There has to be a better way to do this...

def cleanLists(listToClean, extList):
    cleanFileList = []
    for filename in listToClean:
        name = os.path.split(filename)[1]
        ext = os.path.splitext(name)
        if ext[1] in extList:
            name = name.replace(ext[1], '') 
            name = name.replace('1080p', '')
            name = name.replace('1080P', '')
            name = name.replace('720p', '')
            name = name.replace('720P', '')
            name = name.replace('HD', '')
            name = name.replace('(', ' ')
            name = name.replace(')', '')
            name = name.replace('.', ' ')
    cleanFileList.sort(key=lambda x: x.lower())
    return cleanFileList
share|improve this question
add comment

2 Answers

up vote 1 down vote accepted
# do this once
import re
bad_strings = ['1080p', '720p'] # etc
regex = '|'.join(re.escape(x) for x in bad_strings)
subber = re.compile(regex, re.IGNORECASE).sub

# do this once for each name
name = name.replace(ext[1], '')
# OR maybe better: name = ext[0] # see below
cleanFileList.append(subber('', name))

Consider where 'csv' is in your list of extensions and you have a file named 'summary_of_csv_files.csv' ...

share|improve this answer
cleanFileList = [subber('', name) for name in listToClean] # do this once –  agf Jul 25 '11 at 3:31
@agf: omits removing the extension –  John Machin Jul 25 '11 at 3:34
This method works very well! Thanks! I've never used re before, they're kind of scary looking. –  MercuryRising Jul 26 '11 at 2:32
add comment
bad_names = ['1080p', '720p'] # and so on
for bad_name in bad_names:
    name = name.replace(bad_name, '')

Obviously, your declaration of words to clean from each name would happen at the top of the function, not for each iteration over the list of file names.

share|improve this answer
+1 Just reminding that replace returns a copy. –  junjanes Jul 25 '11 at 2:10
@junjanes nice catch, I left that out in my haste –  Rafe Kettler Jul 25 '11 at 2:36
the only thing I would change would be bad_names as a tuple :) –  Hassek Jul 25 '11 at 2:47
@Hassek any reason why? –  Rafe Kettler Jul 25 '11 at 2:50
tuples are lighter since you cant add any more data to them dynamically. making them a good match for a list of constants like this one :) –  Hassek Jul 25 '11 at 6:07
add comment

Your Answer


