create graphviz image from textfile

inspired by text2mindmap.com i decided to create something similar in python.

Here’s the result:

Code text2mindmap.py

#!/usr/bin/python
 
import pydot
import sys
 
 
def ReadFile(filename):
  fh = open(filename)
  return [x.rstrip() for x in fh.readlines()]
 
 
def CreateEdges(lines):
  edge_list= ['' for x in range(100)]
 
  edges = []
  for line in lines:
    pos = line.count('\t');
    edge_list[pos] = line.replace('\t', '')
    if pos:
      edges.append((edge_list[pos -1], edge_list[pos]))
  return edges
 
 
def CreateGraphFromEdges(edges, output):
  g=pydot.graph_from_edges(edges, directed=True)
  return g.write_png('%s.png' % output, prog='dot')    
 
 
def main(argv):
  CreateGraphFromEdges(CreateEdges(ReadFile(argv[1])), argv[2])
 
 
if __name__ == "__main__":
   main(sys.argv)

Source file months.txt

Months of the year
	Spring
		March
		April
		May
	Summer
		June
		July
		August
	Autumn
		September
		October
		November
	Winter
		December
		January
		February

How to generate the image:

$ ./text2mindmap.py months.txt months

Leave a Reply