fork download
  1. import csv
  2. from time import sleep
  3.  
  4. class convert(object):
  5.  
  6. content = []
  7. name = ''
  8.  
  9. def csvInput(self,user):
  10.  
  11. if user.endswith('.csv') == True:
  12. self.name = user.replace('.csv', '')
  13.  
  14. print 'Opening CSV file.'
  15. try:
  16. with open(user, 'rb') as csvfile:
  17. lines = csv.reader(csvfile, delimiter = ',')
  18. for row in lines:
  19. self.content.append(row)
  20. csvfile.close()
  21. except IOError:
  22. print 'File not found.\n'
  23.  
  24. def arffOutput(self):
  25. print 'Converting to ARFF file.\n'
  26. title = str(self.name) + '.arff'
  27. new_file = open(title, 'w')
  28.  
  29. ##
  30. #following portions formats and writes to the new ARFF file
  31. ##
  32.  
  33. #write relation
  34. new_file.write('@relation ' + str(self.name)+ '\n\n')
  35.  
  36. #get attribute type input
  37. for i in range(len(self.content[0])-1):
  38. new_file.write('@attribute ' + str(self.content[0][i]) + '\n')
  39.  
  40. #create list for class attribute
  41. last = len(self.content[0])
  42. class_items = []
  43. for i in range(len(self.content)):
  44. name = self.content[i][last-1]
  45. if name not in class_items:
  46. class_items.append(self.content[i][last-1])
  47. else:
  48. pass
  49. del class_items[0]
  50.  
  51. string = '{' + ','.join(sorted(class_items)) + '}'
  52. new_file.write('@attribute ' + str(self.content[0][last-1]) + ' ' + str(string) + '\n')
  53.  
  54. #write data
  55. new_file.write('\n@data\n')
  56.  
  57. del self.content[0]
  58. for row in self.content:
  59. new_file.write(','.join(row) + '\n')
  60.  
  61. #close file
  62. new_file.close()
  63.  
  64.  
  65. #####
  66. run = convert()
  67. run.csvInput
  68. run.arffOutput
  69.  
  70.  
  71.  
Success #stdin #stdout 0.04s 63940KB
stdin
Standard input is empty
stdout
Standard output is empty