如何根据文件名创建标记非结构化数据集的csv文件

问题描述 投票:1回答:1

我有一个由音频文件组成的非结构化数据集。如何遍历给定目录中的所有文件(包括子文件夹中的所有文件)并根据文件名标记它们,然后将此信息存储在CSV文件中?

我希望CSV文件看起来像this CSV File

enter image description here

python csv dataset label
1个回答
1
投票

目的是我想获取文件名并按照我想要的方式创建标签(对于我的所有文件)然后将此信息保存在csv文件中

您可以使用globpandas to_csv()执行此任务,即:

from os import path
from glob import glob
import pandas as pd

f_filter = ["mp3", "ogg"] # a list containing the desired file extensions to be matched
m = [] # final match list

for f_path in glob('D:/museu_do_fado/mp3/**', recursive=True): # loop directory recursively
    f_name = path.basename(f_path) # get the filename
    f_ext = f_name.split(".")[-1].lower() # get the file extension and lower it for comparison.

    if f_ext in f_filter: # filter files by f_filter 

        label = "Your choice"
        #label = f_name[0] + f_ext[-1] # as per your example, first char of file_name and last of file_ext
        m.append([f_path, f_name, f_ext, label]) # append to match list
        #print(f_path, f_name, f_name, label)

df = pd.DataFrame(m, columns=['f_path', 'f_name', 'f_ext', 'label']) # create a dataframe from match list
df.to_csv("my_library.csv", index=False) # create csv from df

样本csv

f_path,f_name,f_ext,label
D:\museu_do_fado\mp3\MDF0001_39.mp3,MDF0001_39.mp3,mp3,Your choice
D:\museu_do_fado\mp3\MDF0001_40.mp3,MDF0001_40.mp3,mp3,Your choice
...

笔记:

  1. Pandas允许several export formats,包括上面例子中使用的to_json()to_pickle()to_csv(),它是一个很棒的库,可以创建几种类型的data analysis/visualization库。如果可以的话,我明确建议你学习熊猫。
  2. 这个答案应该给你一个起点,确保你read the docs,如果有什么事情,GL。
© www.soinside.com 2019 - 2024. All rights reserved.