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.wrap.py
text/x-python

Download raw (1.6 KB)

import re
import argparse
import textwrap

parser = argparse.ArgumentParser()
parser.add_argument('input', type=argparse.FileType('r'), help="The text-file to parse")
parser.add_argument('output', type=argparse.FileType('w'), help="The dot-file to store produced dot in.")

args = parser.parse_args()

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('"{}"'.format(child.data.replace('"', '\\"')))

      return '"{}" -- {{ {} }}\n{}'.format(self.data.replace('"', '\\"'), ' '.join(labels), '\n'.join(dotcodes))
    else:
      return None

tree = None

for line in args.input.readlines():
  match = re.search('^(\s*)(.*?)$', line)
  head = match.group(1)
  level = len(head) if head else 0
  data = '\n'.join(textwrap.wrap(match.group(2), width=30))

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

args.output.write("graph {{\n {} \n}}".format(tree.toDot()))