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

yipeiwu_com6年前Python基础

本文实例为大家分享了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) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中partial()基础用法说明

前言 一个函数可以有多个参数,而在有的情况下有的参数先得到,有的参数需要在后面的情景中才能知道,python 给我们提供了partial函数用于携带部分参数生成一个新函数。 在funct...

解决Python 使用h5py加载文件,看不到keys()的问题

python 3.x 环境下,使用h5py加载HDF5文件,查看keys,如下: >>> import h5py >>> f = h5py.Fil...

Python中使用摄像头实现简单的延时摄影技术

Python中使用摄像头实现简单的延时摄影技术

延时摄影(英语:Time-lapse photography)是以一种较低的帧率拍 下图像或者视频,然后用正常或者较快的速率播放画面的摄影技术。在一段延时摄影视频中,物体或者景物缓慢变化...

详解Django中六个常用的自定义装饰器

装饰器作用 decorator是当今最流行的设计模式之一,很多使用它的人并不知道它是一种设计模式。这种模式有什么特别之处? 有兴趣可以看看Python Wiki上例子,使用它可以...

python画蝴蝶曲线图的实例

python画蝴蝶曲线图的实例

蝴蝶曲线是由Temple H·Fay发现的可用极坐标函数表示的蝴蝶曲线。 由于此曲线优美, 因此就想把它作为博客favicon.ico,这里我使用pytho matplotlib.pyp...