gpt4 book ai didi

python实现txt文件格式转换为arff格式

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 64 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python实现txt文件格式转换为arff格式由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例为大家分享了python实现txt文件格式转换为arff格式的具体代码,供大家参考,具体内容如下 。

将文件读取出来的时候默认都是字符型的,所以有转换出来有点问题,但是还是可以用的.

文件要求第一行是你对应的属性名,之后是数字.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.

原文链接:https://blog.csdn.net/chichoxian/article/details/41937581 。

最后此篇关于python实现txt文件格式转换为arff格式的文章就讲到这里了,如果你想了解更多关于python实现txt文件格式转换为arff格式的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

64 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com