[英]How to print a reversed ascii tree?
asciitree draws ASCII trees as follows: asciitree绘制ASCII树如下:
root
+--sub1
+--sub2
| +--sub2sub1
+--sub3
+--sub3sub1
| +--sub3sub1sub1
+--sub3sub2
Any hint how to print the 'reversed' tree with python? 任何提示如何使用python打印'reversed'树? Here an example:
这里是一个例子:
sub3sub2--+
sub3sub1sub1--+ |
sub3sub1--+
sub3--+
sub2sub1--+ |
sub2--+
sub1--+
root
asciitree uses following node-structure: asciitree使用以下节点结构:
class Node(object):
def __init__(self, name, children):
self.name = name
self.children = children
You could just invert the output of asciitree
: 您可以只反转
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.