我的 Python 之旅仍处于起步阶段,所以这个问题对于更高级的程序员来说可能是基础。
我想分析一堆 .wav 文件,它们都存储在同一目录中,所以我创建了一个所有文件名的列表,以便我可以获取它们的音频信号和采样率。
dirPath=r"path_to_directory"
global files
files = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f)) and f.endswith(".wav")]
for file_name in files:
path_to_file= dirPath+"\\"+file_name
audio_signal, sample_rate = sf.read(path_to_file)
sf
是 soundfile
库。
audio_signal
是一个数组,sample_rate
是一个数字。
现在我希望能够将 audio_signal
和 sample_rate
与相应的 file_name
一起存储,以便我以后可以访问它们。我该怎么做?
我试过了
files = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f)) and f.endswith(".wav")],[]
for file_name in files[0]:
path_to_file= dirPath+"\\"+file_name
audio_signal, sample_rate = sf.read(path_to_file)
files[1].append(audio_signal)
files[2].append(sample_rate)
这似乎有效,但有没有更优雅的方法?我觉得 audio_signal
、sample_rate
和 file_name
是单独的值而不是相互依赖的。
答案 0 :(得分:0)
您正在寻找的数据结构是一个关联数组,它将键与值相关联——键是文件名和在这个例子中,值是一个由音频信号和采样率组成的元组。
关联数组的实现作为 dictionary 类型内置到 Python 中。
您可以在此处了解词典: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
您代码中的应用程序如下所示:
$36,294.89
$2,216.34
$0.002825
$0.721100
$0.267331