2014-03-12 40 views
0

asciitree绘制ASCII树如下:如何打印反向ascii树?

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

任何暗示如何打印“逆转”与蟒蛇树?下面一个例子:

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

asciitree使用以下节点结构:

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

有你尝试过任何你自己呢? –

+0

是的,我已经开始修改[asciitree._draw_tree]的代码(https://github.com/mbr/asciitree/blob/master/asciitree.py#L16),但是我搜索了一个算法来帮助计算rtl节点间距。我相信在之前的一些pydocs(?)文档中已经看到了这种类层次结构以这种方式打印的情况。任何提示? – wolfrevo

回答

1

你可能只是反转的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) 

演示:

>>> 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 
+0

是的。这正是我想要的!谢谢! – wolfrevo