python实现txt文件格式转换为arff格式
程序员文章站
2023-08-14 20:15:49
本文实例为大家分享了python实现txt文件格式转换为arff格式的具体代码,供大家参考,具体内容如下
将文件读取出来的时候默认都是字符型的,所以有转换出来有点问题,但...
本文实例为大家分享了python实现txt文件格式转换为arff格式的具体代码,供大家参考,具体内容如下
将文件读取出来的时候默认都是字符型的,所以有转换出来有点问题,但是还是可以用的。
文件要求第一行是你对应的属性名,之后是数字。
import sys import re relationname = "" filename = "" if (len(sys.argv)<2): print("usage:\npython arff.py myrelationname filename.txt") else: relationname = sys.argv[1] filename = sys.argv[2] class arff: def __init__(self, r, f): self.relationname = r if r is not "" else "machinelearning" f = f if f is not "" else "mmg_data.txt" self.file1 = open(f, 'r') self.data = [] self.names = [] self.parsedata() self.writetofile() def parsedata(self): firstline = true for line in self.file1.readlines(): if not firstline: try: line = line.replace("\n", "") words = line.split(" ") except valueerror: print("cant parse file!!") self.data.append(words) else: firstline = false line = line.replace("\n", "") words = line.split(" ") self.names = words def gettype(self, value): v = "" if(type(value) == type(1)): v = "numeric" elif(type(value) == type(1.0)): v = "numeric" elif(re.match("[0-9]{4}\-[0-9]{2}\-[0-9]{2}\s[0-9]{2}\:[0-9]{2}\:[0-9]{2}", value)): v = "date " + "yyyy-mm-dd hh:mm:ss" elif(type(value) == type("string")): v = "string" elif(v == ""): print("data type "+value+" not supported yet.") return v def writetofile(self): values = self.data[0] file2 = open("dexhunter_test_result.arff", 'w+' ) self.relationname+="\n" relationstring = '@relation ' + self.relationname file2.write(''+relationstring+'') for i in range(len(self.names)): str2 = "@attribute " + self.names[i] + " " + self.gettype( values[i] ) + "\n" file2.write(''+str2+'') file2.write('''''@data\n''') for line in self.data: try: file2.write(",".join(line)+"\n") except unicodeencodeerror: print("cant write data to file!!") arff(relationname, filename)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。