我有一个工作脚本,可从文件中剥离“ TRASH”。但是它是CLUNKY,如果您想更改“ TRASH”,那就很麻烦。是否有关于如何清理此代码的想法?也许有列表或字典?
要清除的文件名: 2Pac-All Eyez On Me(带有LyrIcs的官方卡拉OK视频)-_ z1tdf8Gn6Y.mp4
import os os.chdir("C:/Users/Suppe/OneDrive/Documents/Kerokey")#change working directory. for f in os.listdir(): #file list. f2 = f.lower() #make lowercase to compare text. file_name, File_ext = (os.path.splitext(f2)) #strip file extension. file_name = file_name.strip()[0:-12] #Strip the _z1tdf8Gn6Y off. n_beg, n_mid, n_end = file_name.partition("karaoke") #break the name with TRASH. file_name = ('{}{}'.format(n_beg, n_end)) #put name back together. n_beg, n_mid, n_end = file_name.partition("official")#repeat everything over. file_name = ('{}{}'.format(n_beg, n_end)) n_beg, n_mid, n_end = file_name.partition("video") file_name = ('{}{}'.format(n_beg, n_end)) n_beg, n_mid, n_end = file_name.partition("version") file_name = ('{}{}'.format(n_beg, n_end)) n_beg, n_mid, n_end = file_name.partition("lyrics") file_name = ('{}{}'.format(n_beg, n_end)) n_beg, n_mid, n_end = file_name.partition("with") file_name = ('{}{}'.format(n_beg, n_end)) file_name.strip() print(file_name.capitalize()) #Reformat the name. #HAVEN'T GOTTEN ANY FARTHER YET.
文件名输出: 2pac-所有人都盯着我()
最后,我需要删除结尾处的“()”,并添加文件扩展名,以便我可以使用新名称保存文件: 2pac-众目eye。 mp4
答案 0 :(得分:0)
我为您提供了一个非常简单的解决方案:
var = "2pac - all eyez on me ()"
if "()" in var:
var = var.replace(" ()", ".mp4")
print(var)