gpt4 book ai didi

python - 如何从列表中的字符串中删除数字并再次检索它们

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:06 25 4
gpt4 key购买 nike

好的,场景如下:我正在制作一个 Windows 7 程序,该程序搜索目录中的所有音乐文件,并根据该列表检查用户的输入,以便它可以播放用户选择的歌曲。因为轨道的名称通常是这样编号的,例如:“01 name.mp3”,所以我想从新列表中删除“01”部分,并让程序记录“01”,以便它可以从新列表并启动文件。换句话说,我希望程序创建一个不带数字的新文件名列表,并让程序识别该文件并通过知道该数字来启动它。这可能吗? (告诉我这是否没有任何意义。)另外,这是我的一些代码:

def GetMediaFName(source, name):
for key, val in source.iteritems():
if val == name:
return key

newList = {}
media_list = []
for dirpath, dirnames, filenames in os.walk(music_dir) and os.walk(alt_music_dir1):
for filename in [f for f in filenames if f.endswith(".m4a") or f.endswith(".mp3") or f.endswith(".mp4")]:

media_list.append(os.path.join(dirpath, filename))



media_from_menu = menu[5:]
print(media_from_menu)
media_to_search1 = media_from_menu + ".mp3"
media_to_search2 = media_from_menu + ".wav"
media_to_search3 = media_from_menu + ".m4a"
media_to_search4 = media_from_menu + ".mp4"

for i in media_list:
spl = i.split('\\')[-1]
if spl is not None:
try:
tmp = re.findall(r'\d+',spl.split('.')[0][0])
newList.update({i:i.replace(tmp,"").strip()})
except Exception:
newList.update({i:spl})

itms = newList.keys()

for i in files:
tmp = re.findall(r'\d+',i.split('.')[0][0])
newList.update({i:i.replace(tmp,"").strip()})
print(newList)

print(GetMediaFName(newList, media_from_menu + ".mp3"))

最佳答案

我不确定我是否理解正确,但您想在向用户显示不同的名称(假设没有索引号的轨道名称)的同时跟踪原始文件名。

我想这可能会让您对此有所了解。您要使用一些 GUI 库吗?

import re

def getFileName(source,name):
for key,val in source.iteritems():
if val == name:
return key

names = ['01 name_a.mp3','02 name_b.mp3','03 name_c.mp3','04 name_d.mp3']

newList = {}

for i in names:
tmp = re.findall(r'\d+',i.split('.')[0])[0]
newList.update({i:i.replace(tmp,"").strip()})

print newList

# If names are not the same, but you run in trouble if all of tracks are 01 name.mp3 , 02 name.mp3 and so on

print getFileName(newList,'name_a.mp3')

# Another possible way ! get the index of element user has clicked on and pass it to a list of original file names
user_selected = 2
itms = newList.keys()
print itms[user_selected]

编辑:

要查找特定路径中的 Mp3(包括其子目录中的文件):

import os
import os.path
import re

def getFileName(source,name):
for key,val in source.iteritems():
if val == name:
return key


names = []
# From : http://stackoverflow.com/a/954522/3815839
for dirpath, dirnames, filenames in os.walk("C:\Users\test\Desktop\mp3s"):
for filename in [f for f in filenames if f.endswith(".mp3")]:
names.append(os.path.join(dirpath, filename))

newList = {}
for i in names:
spl = i.split('\\')[-1]
if spl is not None:
try:
tmp = re.findall(r'\d+',spl.split('.')[0])[0]
newList.update({i:i.replace(tmp,"").strip()})
except Exception:
newList.update({i:spl})
itms = newList.keys()
print newList

print getFileName(newList,'name_a.mp3')

关于python - 如何从列表中的字符串中删除数字并再次检索它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com