-
Notifications
You must be signed in to change notification settings - Fork 2
/
arff_parser.py
executable file
·187 lines (165 loc) · 4.29 KB
/
arff_parser.py
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
import sys,json
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
FILE_ERROR=0
OPTION_ERROR=1
OTHER_ERROR=2
DEBUG = False
legal_options = {"formats":["-xml","-json"],"debug":["--debug"]}
error_array = ["Invalid file extension - expects '<filename>.arff'","Invalid option - expects '-json' or '-xml'.","The file format is invalid."]
errors = open("stderr","w")
error_log = []
line_count = 0
def build_output(schema,outfile,opts):
JSON = ("-json" in opts)
if JSON:
output_json(schema, outfile)
else:
output_xml(schema,outfile)
def build_nodes(data, name):
# Recurse through data and build DOM tree.
output=[]
parent = ET.Element(name)
if(isinstance(data,list)):
console("list")
for item in data:
if(name=="values"):
tagname="value"
elif(name=="attributes"):
tagname="attribute"
elif(name=="data"):
tagname = "entry"
else:
tagname = name
output.append(build_nodes(item,name=tagname))
elif(isinstance(data,dict)):
for attr in data:
output.append(build_nodes(data[attr],name=attr))
if (len(output)>0):
for entry in output:
t = ET.ElementTree(entry)
t.write(errors)
parent.extend(tuple(output))
else:
parent.text=data
return parent
def output_xml(schema,outfile):
root = build_nodes(schema,'dataset')
if not (root):
console("root was null and I don't know why.")
roottree = ET.ElementTree(root)
roottree.write(outfile)
def exit_with_errors():
"""docstring for exit_with_errors"""
for error in error_log:
console("Error at " + error['line_num']+":")
console(error["message"])
console(error["details"])
sys.exit()
def get_filenames(args):
"""docstring for get_filenames"""
filenames = []
for arg in args:
if not arg[0]=='-':
if has_valid_extension(arg):
filenames.append(arg)
else:
log_error(0,FILE_ERROR, "Please check the file extension and try again.")
exit_with_errors()
return filenames
def get_options(args):
"""docstring for get_options"""
options = []
for arg in args:
if arg[0]=='-':
for option in legal_options:
if(is_legal(option, arg)):
options.append(arg)
return options
def has_valid_extension(path):
"""docstring for has_valid_extension"""
filename = name_from_path(path)
parts = filename.split(".")
if(len(parts)<1):
return False
elif(parts[len(parts)-1]=="arff"):
return True
else:
return False
def is_legal(option, arg):
return arg in legal_options[option]
"""docstring for is_legal"""
def console(msg):
errors.write(str(msg))
errors.write("\n")
def log_error(line_num,error_index, details):
"""docstring for log_error"""
this_error = {"line_num":line_num,"message":error_array,"details":details}
error_log.append(this_error)
def name_from_path(path):
"""docstring for name_from_path"""
result = path
substr = path.split("/")
if(len(substr)>0):
return substr[len(substr)-1]
return result
def output_json(schema,outfile):
outfile.write(json.dumps(schema))
def process(filename, opts):
readdata = False
handle = filename.split(".")[0]
if "-json" in opts:
handle = handle + ".json"
else:
handle = handle + ".xml"
if "--debug" in opts:
DEBUG = True
infile = open(filename,'r')
outfile = open(handle,'w')
schema = {"relation":"","attributes":[],"data":[]}
for line in infile:
if(line[0]=="%"):
continue
elif(line[0]=="@"):
args = line.split()
if (args[0]=="@relation"):
schema["relation"]=args[1]
elif(args[0]=="@attribute"):
values = "".join(args[2:])
if(values[0]=="{"):
values = values[1:len(values)-1]
values = values.split(",")
schema["attributes"].append({"name":args[1],"values":values})
elif(args[0]=="@data"):
readdata=True
elif(readdata):
schema["data"].append(line.strip())
if(DEBUG):
show_schema(schema)
names = []
data = []
attrs = schema["attributes"]
for attr in attrs:
names.append(attr["name"])
for row in schema["data"]:
row = row.split(",")
entry = {}
for name in names:
entry[name] = row[names.index(name)]
data.append(entry)
schema["data"] = data
build_output(schema,outfile,opts)
def show_schema(schema):
"""debug"""
for field in schema:
console(field, schema[field])
def main():
args = sys.argv[1:]
file_args = get_filenames(args)
opts = get_options(args)
for filename in file_args:
process(filename, opts)
main()