python写文件格式转换程序_python实现txt文件格式转换为arff格式
本文實(shí)例為大家分享了python實(shí)現(xiàn)txt文件格式轉(zhuǎn)換為arff格式的具體代碼,供大家參考,具體內(nèi)容如下
將文件讀取出來(lái)的時(shí)候默認(rèn)都是字符型的,所以有轉(zhuǎn)換出來(lái)有點(diǎn)問(wèn)題,但是還是可以用的。
文件要求第一行是你對(duì)應(yīng)的屬性名,之后是數(shù)字。
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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
本文標(biāo)題: python實(shí)現(xiàn)txt文件格式轉(zhuǎn)換為arff格式
本文地址: http://www.cppcns.com/jiaoben/python/229365.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的python写文件格式转换程序_python实现txt文件格式转换为arff格式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: uos命令_ubuntu、debian、
- 下一篇: GUI文本框输入