【问题标题】:Is there a way to automatically generate an empty array for each iteration of a for loop?有没有办法为 for 循环的每次迭代自动生成一个空数组?
【发布时间】:2019-10-18 20:07:29
【问题描述】:

我正在尝试为 for 循环的每次传递创建一个单独的数组,以存储由 wavefile.read 函数生成的“信号”值。

关于代码如何工作/我喜欢它如何工作的一些背景知识:

我有以下文件路径:

Root directory 
    Labeled directory
        Irrelevant multiple directories
            Multiple .wav files stored in these subdirectories

    Labeled directory
        Irrelevant multiple directories
            Multiple .wav files stored in these subdirectories

现在对于每个带标签的文件夹,我想创建一个数组来保存其各自子目录中包含的所有 .wav 文件的值。

这是我尝试的:

for label in df.index:

    for path, directories, files in os.walk('voxceleb1/wav_dev_files/' + label):
        for file in files:
            if file.endswith('.wav'):
                count = count + 1
                rate,signal = wavfile.read(os.path.join(path, file))

print(count)

上面是数据帧df的快照

最终,这些数组的原因是我想计算每个标记的子目录中包含的 wav 文件的平均平均时间长度,并将其作为列向量添加到数据帧中。

请注意,数据框的索引对应于目录名称。我感谢任何和所有的帮助!

【问题讨论】:

  • 我没有完全按照您的要求进行操作,但怀疑您最好将文件值收集在列表或字典中,而不是 numpy 数组中。一个空列表是[],列表追加是一种将对象添加到列表的有效方式。

标签: python pandas scipy librosa


【解决方案1】:

您发布的代码 sn-p 可以稍微简化和现代化。这是我想出的:

我有以下目录结构:

在我的示例中,我使用的是文本文件而不是 wav 文件,因为我手头没有任何 wav 文件。 在我的root 中,我有AB(这些应该是您的“标记目录”)。 A 有两个文本文件。 B 有一个直接文本文件和一个子文件夹,其中包含另一个文本文件(这是为了模拟您的“不相关的多个目录”)。

代码:

def main():

    from pathlib import Path

    root_path = Path("./root/")
    labeled_directories = [path for path in root_path.iterdir() if path.is_dir()]

    txt_path_lists = []

    # Generate lists of txt paths
    for labeled_directory in labeled_directories:
        txt_path_list = list(labeled_directory.glob("**/*.txt"))
        txt_path_lists.append(txt_path_list)

    # Print the lists of txt paths
    for txt_path_list in txt_path_lists:
        print(txt_path_list)

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

[WindowsPath('root/A/a_one.txt'), WindowsPath('root/A/a_two.txt')]
[WindowsPath('root/B/b_one.txt'), WindowsPath('root/B/asdasdasd/b_two.txt')]

如您所见,我们生成了两个文本文件路径列表,每个标记目录对应一个。我使用的 glob 模式 (**/*.txt) 处理多个嵌套目录,并递归查找所有文本文件。您所要做的就是更改 glob 模式中的扩展名,让它找到 .wav 文件。

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2013-09-19
    • 2019-06-05
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多