species-of-things
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

todot.py
text/x-python

Download raw (1.7 KB)

import re
import argparse
import urllib

parser = argparse.ArgumentParser()
parser.add_argument('input', type=str, help="The text-file to parse")
parser.add_argument('output', type=str, help="The dot-file to store produced dot in.")
args = parser.parse_args()
is_url_match = r'^http(?:s)?:\/\/'
filein = urllib.urlopen(args.input) if re.match(is_url_match, args.input) else open(args.input, 'r')

class Node (object):
  def __init__ (self, data = '', parent=None, level=0):
    self.parent = parent
    self.data = data
    self.children = []
    self.level = level

  def lastChild(self):
    if self.children:
      return self.children[-1];
    return None 

  def include (self, data, level):
    # print data, level, self.level
    if ((level - self.level > 1) and self.children):
      self.lastChild().include(data, level)
    else:
      self.children.append(Node(data=data, parent=self, level=self.level+1))

  def toDot (self):
    if len(self.children) > 0:
      dotcodes = []
      labels = []
      for child in self.children:
        if child.children:
          dotcodes.append(child.toDot())
        labels.append('"{}" [shape="box"]'.format(child.data.replace('"', '\\"')))

      return '"{}" [shape="box"] subgraph {{ {} }}'.format(self.data.replace('"', '\\"'), '\n'.join(dotcodes))
    else:
      return None

tree = None

for line in filein.readlines():
  match = re.search('^(\s*)(.*?)$', line)
  head = match.group(1)
  level = (len(head))/8 if head else 0
  data = match.group(2)

  if not tree:
    tree = Node(data=data, level=level)
  else:
    tree.include(data, level)

with open(args.output, 'w') as output:
  output.write("graph {{\n {} \n}}".format(tree.toDot()))