简体   繁体   中英

How to print a reversed ascii tree?

asciitree draws ASCII trees as follows:

root
  +--sub1
  +--sub2
  |  +--sub2sub1
  +--sub3
     +--sub3sub1
     |  +--sub3sub1sub1
     +--sub3sub2

Any hint how to print the 'reversed' tree with python? Here an example:

       sub3sub2--+
sub3sub1sub1--+  |
       sub3sub1--+
              sub3--+
       sub2sub1--+  |
              sub2--+
              sub1--+
                 root

asciitree uses following node-structure:

class Node(object):
    def __init__(self, name, children):
        self.name = name
        self.children = children

You could just invert the output of asciitree :

lines = output.splitlines()[::-1]
width = max(len(l) for l in lines)

reversed = []
for line in lines:
    tree, dashes, label = line.rpartition('--')
    tree = (tree + dashes)[::-1]
    line = '{1:>{0}}{2}'.format(width - len(tree), label, tree).rstrip()
    reversed.append(line)

print '\n'.join(reversed)

Demo:

>>> output = '''\
... root
...   +--sub1
...   +--sub2
...   |  +--sub2sub1
...   +--sub3
...      +--sub3sub1
...      |  +--sub3sub1sub1
...      +--sub3sub2
... '''
>>> lines = output.splitlines()[::-1]
>>> width = max(len(l) for l in lines)
>>> reversed = []
>>> for line in lines:
...     tree, dashes, label = line.rpartition('--')
...     tree = (tree + dashes)[::-1]
...     line = '{1:>{0}}{2}'.format(width - len(tree), label, tree).rstrip()
...     reversed.append(line)
... 
>>> print '\n'.join(reversed)
       sub3sub2--+
sub3sub1sub1--+  |
       sub3sub1--+
              sub3--+
       sub2sub1--+  |
              sub2--+
              sub1--+
                   root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM