Iterate through two lists, check for matches and t

2019-07-26 14:11发布

问题:

Ok, so I have two lists; one is a list of song titles, the other is a list of files that is generated by running os.listdir(), which will be song mp3 files.

UPDATED

songs = ['The Prediction', 'Life We Chose', 'Nastradamus', 'Some of Us Have Angels', 'Project Windows', 'Come Get Me', "Shoot 'em Up", 'Last Words', 'Family', 'God Love Us', 'Quiet Niggas', 'Big Girl', 'New World', 'You Owe Me', 'The Outcome']

Each song is unicode

filenames = ['Nas - Big Girl.mp3', 'Nas - Come Get Me.mp3', 'Nas - God Love Us.mp3', 'Nas - Life We Chose.mp3', 'Nas - Nastradamus.mp3', 'Nas - New World.mp3', "Nas - Shoot 'Em Up.mp3", 'Nas - Some of Us Have Angels.mp3', 'Nas - The Outcome.mp3', 'Nas - The Prediction.mp3', 'Nas Feat. Bravehearts - Quiet Niggas.mp3', 'Nas Feat. Ginuwine - You Owe Me.mp3', 'Nas Feat. Mobb Deep - Family.mp3', 'Nas Feat. Nashawn - Last Words.mp3', 'Nas Feat. Ronald Isley - Project Windows.mp3']

Each filename is a string

I want to be able to look at the songs list, if one of the items from the songs list matches inside the filenames list, rename the file to that of the song.

Does that make sense?

回答1:

Basically it looks like this:

import os

for song in songs:
    for filename in filenames:
        if song.lower() in filename.lower():  # lower() just in case
            os.rename(filename, song + '.mp3')

If you need anything else, please ask.