ARFF 到 CSV 多文件转换

ARFF to CSV multiple files conversions

有人成功地尝试从 windows 命令行将许多 ARFF 文件转换为 CSV 文件。

我尝试使用 weka.core.converters.CSVSaver 但它仅适用于单个文件。

多个文件可以吗?

在 windows 命令行上,键入 powershell

切换到您的 *.arff 文件所在的目录

输入此命令

dir *.arff | Split-Path -Leaf| ForEach-Object {Invoke-Expression "C:\Program Files\Weka-3-6\weka.jar;." weka.core.converters.CSVSaver -i $_ -o $_.csv"}

这假定您的文件名不包含任何空格,并且所有 arff 文件都位于一个目录中,并且您希望将它们全部转换。它将从每个 arff 文件创建一个新的 csv 文件。 myfile.arff 将是 exported/converted 到 myfile.arff.csv

我找到了一种使用 R 来解决此转换的方法,如下面的脚本所示:

#### Set the default directory to the folder that contains all ARFF files 

temp = list.files(pattern="*.arff")
library(foreign)

for (i in 1:length(temp)) assign(temp[i], read.arff(temp[i]))

for(i in 1:length(temp))
{
mydata=read.arff(temp[i])
t=temp[i]
x=paste(t,".csv")
write.csv(mydata,x,row.names=FALSE)
mydata=0
}

我在 github: arff2csv.py 中写了一个简单的 python 脚本。

粘贴我的代码。

"""trans multi-label *.arff file to *.csv file."""
import re


def trans_arff2csv(file_in, file_out):
    """trans *.arff file to *.csv file."""
    columns = []
    data = []
    with open(file_in, 'r') as f:
        data_flag = 0
        for line in f:
            if line[:2] == '@a':
                # find indices
                indices = [i for i, x in enumerate(line) if x == ' ']
                columns.append(re.sub(r'^[\'\"]|[\'\"]$|\+', '', line[indices[0] + 1:indices[-1]]))
            elif line[:2] == '@d':
                data_flag = 1
            elif data_flag == 1:
                data.append(line)

    content = ','.join(columns) + '\n' + ''.join(data)

    # save to file
    with open(file_out, 'w') as f:
        f.write(content)


if __name__ == '__main__':
    from multi_label.arff2csv import trans_arff2csv

    # setting arff file path
    file_attr_in = r'D:\Downloads\birds\birds-test.arff'
    # setting output csv file path
    file_csv_out = r"D:\Downloads\birds\birds-test.csv"
    # trans
    trans_arff2csv(file_attr_in, file_csv_out)