本文實(shí)例為大家分享了python實(shí)現(xiàn)txt文件格式轉(zhuǎn)換為arff格式的具體代碼,供大家參考,具體內(nèi)容如下
成都創(chuàng)新互聯(lián)網(wǎng)站建設(shè)服務(wù)商,為中小企業(yè)提供成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)服務(wù),網(wǎng)站設(shè)計(jì),綿陽(yáng)服務(wù)器托管等一站式綜合服務(wù)型公司,專業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競(jìng)爭(zhēng)對(duì)手中脫穎而出成都創(chuàng)新互聯(lián)。將文件讀取出來(lái)的時(shí)候默認(rèn)都是字符型的,所以有轉(zhuǎn)換出來(lái)有點(diǎ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)
網(wǎng)頁(yè)名稱:python實(shí)現(xiàn)txt文件格式轉(zhuǎn)換為arff格式-創(chuàng)新互聯(lián)
分享地址:http://jinyejixie.com/article28/isdcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、微信小程序、網(wǎng)站策劃、品牌網(wǎng)站設(shè)計(jì)、企業(yè)網(wǎng)站制作、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容