Skip to content

Commit b8d45e0

Browse files
committed
Python script for visualising a Trie
1 parent e1c5ae3 commit b8d45e0

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

input.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
abbrevia
2+
baba
3+
baba.ba

trie_vis.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
'''
2+
A small program to visualize a trie data structure in the form of decision tree graph.
3+
'''
4+
#imports
5+
import json
6+
import pydot
7+
8+
# function to return a new dict template
9+
def struct():
10+
struct = {
11+
12+
}
13+
return struct
14+
15+
# getting list of words as input from the file
16+
file_ = open('./input.txt', 'r')
17+
file_text = file_.read()
18+
file_len = len(file_text)
19+
file_.close()
20+
21+
# trie making stuff happening (hard to explain)
22+
tmp_s = struct()
23+
root = tmp_s
24+
for line in file_text.split('\n'):
25+
for c in line.split('.'):
26+
if c not in tmp_s:
27+
tmp_s[c] = struct()
28+
tmp_s = tmp_s[c]
29+
tmp_s = root
30+
cur_word = []
31+
32+
# saving the trie in a json file
33+
with open('output.json', 'w') as fp:
34+
json.dump(root, fp, indent=4)
35+
36+
# converting and saving the trie to dot language decision tree graph using pydot
37+
# // code taken and modified from stackoverflow (https://stackoverflow.com/questions/13688410/dictionary-object-to-decision-tree-in-pydot)
38+
rt = {'': root}
39+
counter = 0
40+
def draw(parent_name, child_name):
41+
global counter
42+
counter += 1
43+
p_n = parent_name
44+
c_n = child_name
45+
graph.add_node(pydot.Node(p_n, label=parent_name.split('_')[0]))
46+
graph.add_node(pydot.Node(c_n, label=child_name.split('_')[0]))
47+
edge = pydot.Edge(p_n, c_n)
48+
graph.add_edge(edge)
49+
50+
def visit(node, parent=None):
51+
global counter
52+
for k,v in node.items():
53+
if isinstance(v, dict):
54+
# We start with the root node whose parent is None
55+
# we don't want to graph the None node
56+
k = k + '_' + str(counter)
57+
if parent:
58+
draw(parent, k)
59+
visit(v, k)
60+
else:
61+
# drawing the label using a distinct name
62+
v = v + '_' + str(counter)
63+
draw(parent, v)
64+
65+
graph = pydot.Dot(graph_type='digraph')
66+
visit(rt)
67+
graph.write_pdf('output.pdf')
68+
69+
# end of program

0 commit comments

Comments
 (0)