Python:在字符串列表中查找子字符串 [英] Python: Find substring in list of string

查看:197
本文介绍了Python:在字符串列表中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表: songs 是歌曲标题列表, filenames 是通过运行 os.listdir().

I have two lists: songs is a list of song titles, filenames is a list of song MP3 files that is generated by running os.listdir().

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']

每首歌都是unicode.

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.

如果 songs 列表中的一项与 filenames 列表中的项匹配,我希望能够查看 songs 列表,将文件重命名为歌曲的文件.

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.

推荐答案

此处是一个将保留文件扩展名的版本,无论它是什么,并且都会通过从删除相同的文件名来避免两次相同的文件名匹配后的文件名数组.它也不区分大小写:

Here is a version that will maintain the file extension, whatever it was, and will avoid that the same filename is matched twice by deleting it from the filenames array after a match. It also is case insensitive:

for song in songs:
    for i, filename in enumerate(filenames):
        if song.upper() in filename.upper():
            os.rename(filename, song + os.path.splitext(filename)[1])
            del filenames[i]
            break

您也可以先循环搜索文件名,但是问题还可能是两个文件名与同一首歌曲匹配,而 rename 操作将在第二个文件上引发错误.因此,在该设置中,最好将歌曲与文件名匹配后从歌曲列表中删除.

You could also loop first over the file names, but then the problem can also be that two file names match with the same song, and the rename operation will raise an error on the second. So in that set up you'd better delete the song from the songs list once it has been matched with a file name.

这篇关于Python:在字符串列表中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆