forked from JunyiJ/Fault-Tree-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.py
72 lines (65 loc) · 2.31 KB
/
parse.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
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
import sys
import time
# Given an input file, parse it into a xml file, named as the inputfilename_out.txt
# To test the script, type the following command:
# python .\parse.py 'input.txt'
def Parse2xml(infilename):
# Given an input file, parse it into xml file
list=Element('list')
root=SubElement(list,'node')
root.set('id','Root')
root_gate=SubElement(root,'gate')
root_gate.text='AND'
nodes=[]
nodes_child={}
with open(infilename,'r') as f:
for line in f.readlines():
elements=line.strip("<\t />\n").split("=")
if len(elements)>1:
node_id=((elements[1].split(" "))[0]).strip('"\'')
node_route=elements[3].strip('"').split(", ")
#print node_id,node_route
if node_id not in nodes:
nodes.append(node_id)
nodes_child[node_id]=[node_route]
else:
nodes_child[node_id].append(node_route)
for node in nodes:
n=SubElement(root,'dep') #Add new child node under root
n.text=node
if len(nodes_child[node])==1:
Add_Node(list,node,"OR",nodes_child[node][0]) #Add new node under list if no parellel path
else: #Add new node under list if exists parellel path
new_pnode=SubElement(list,'node')
new_pnode.set("id",node)
g=SubElement(new_pnode,'gate')
g.text="AND"
for i in range(len(nodes_child[node])):
count=i+1
subnode_name="%s-path%d"%(node,count)
subnode=SubElement(new_pnode,'dep')
subnode.text=subnode_name
Add_Node(list,subnode_name,"OR",nodes_child[node][i])
outfilename=infilename[:(len(infilename)-4)]+"_out.txt"
with open(outfilename,"w") as f:
ElementTree(list).write(f)
def Add_Node(parentnode,name,gate,child_node):
#Create a new node by providing the following information:
#parentnode, name of the new node,gate("AND","OR"),child_node list
new_node=SubElement(parentnode,'node')
new_node.set('id',name)
g=SubElement(new_node,'gate')
g.text=gate
for c in child_node:
child=SubElement(new_node,'dep')
child.text=c
starttime=time.time()
argv=sys.argv
infilename=argv[1]
Parse2xml(infilename)
endtime=time.time()
timetxt="Parsing time for %s is %s seconds\n"%(infilename,endtime-starttime)
with open("parse_time.txt","a") as f:
f.write(timetxt)
print timetxt