如何打印反向的ASCII树?

0 投票
1 回答
515 浏览
提问于 2025-04-17 21:56

asciitree 可以用来绘制 ASCII 树,效果如下:

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

有没有什么方法可以用 Python 打印出“反转”的树呢?这里有个例子:

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

asciitree 使用了以下的节点结构:

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

1 个回答

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

撰写回答