我尝试列出符合MySample %i %j.wav
的文件夹中的所有文件(其中%i
,%j
应该是整数),而不是像这样的结果(我试过glob.glob('MySample *.wav')
):
["MySample 117 12.wav", "MySample 011 18.wav", "MySample 13 45.wav"]
我希望能够通过模式变量%i,%j 编制索引:
{(117, 12): "MySample 117 12.wav",
(11, 18): "MySample 011 18.wav",
(13, 45) : "MySample 13 45.wav"}
答案 0 :(得分:2)
使用正则表达式相当简单:
import os, re
samples = {}
for f in os.listdir("."):
m = re.match(r"MySample (\d+) (\d+).wav", f)
if m:
samples[tuple(int(x) for x in m.groups())] = f
答案 1 :(得分:0)
您可以使用正则表达式匹配
import re
def getKey(x):
m=re.match ('MySample (\d+) (\d+).wav',x)
if m:
return (m.group(1),m.group(2))
else:
return None
sample=["MySample 117 12.wav", "MySample 011 18.wav", "MySample 13 45.wav"]
然后创建字典的列表理解
r=dict(((getKey(x),x) for x in sample))