python實現(xiàn)txt文件格式轉(zhuǎn)換為arff格式
更新時間:2018年05月31日 10:05:40 作者:君的名字
這篇文章主要為大家詳細介紹了python實現(xiàn)txt文件格式轉(zhuǎn)換為arff格式的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python實現(xiàn)txt文件格式轉(zhuǎn)換為arff格式的具體代碼,供大家參考,具體內(nèi)容如下
將文件讀取出來的時候默認都是字符型的,所以有轉(zhuǎn)換出來有點問題,但是還是可以用的。
文件要求第一行是你對應(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)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python3中bytes和string之間的互相轉(zhuǎn)換
這篇文章主要介紹了python3中bytes和string之間的互相轉(zhuǎn)換,文中給出了詳細的介紹和示例代碼,相信對大家具有一定的參考價值,有需要的朋友們下面來一起學習學習吧。2017-02-02pytorch中LN(LayerNorm)及Relu和其變相的輸出操作
這篇文章主要介紹了pytorch中LN(LayerNorm)及Relu和其變相的輸出操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05Python基于HOG+SVM/RF/DT等模型實現(xiàn)目標人行檢測功能
這篇文章主要介紹了Python基于HOG+SVM/RF/DT等模型實現(xiàn)目標檢測[行人檢測],今天這里并不是說要做出怎樣的效果,而是基于HOG+SVM來實踐機器學習檢測的流程,需要的朋友可以參考下2022-06-06