text-mode tree viewer?

T

Torsten Bronger

Hallöchen!

I'm looking for a package/routine that can convert

[["Peter",
["Ian",
[["Randy",
["Clara"]]]]],
"Paul",
["Mary",
["Arthur"]]]

into

+---> Peter
| |
| +---> Ian
| |
| +---> Randy
| |
| +---> Clara
|
+---> Paul
|
+---> Mary
|
+---> Arthur

Neither the input data structure nor the output must be exactly like
here but probably you got the idea. Thank you for any hints!

Tschö,
Torsten.
 
M

Martin Skou

Not quite, but almost:


data=[["Peter",
["Ian",
[["Randy",
["Clara"]]]]],
"Paul",
["Mary",
["Arthur"]]]


def show(data,level):
for i in data:
if i.__class__.__name__=='list':
show(i,level+1)
else:
print '%s->%s' % ('-'*level,i)


show(data,0)


/Martin
 
T

Torsten Bronger

Hallöchen!

Martin said:
Not quite, but almost:


data=[["Peter",
["Ian",
[["Randy",
["Clara"]]]]],
"Paul",
["Mary",
["Arthur"]]]

This was flawed, there were two brackets too much:

data=[["Peter",
["Ian",
["Randy",
["Clara"]]]],
"Paul",
["Mary",
["Arthur"]]]
def show(data,level):
for i in data:
if i.__class__.__name__=='list':
show(i,level+1)
else:
print '%s->%s' % ('-'*level,i)


show(data,0)

It doesn't show Paul and Mary on the same level. I (think I) solved
the problem with this:

def print_tree(tree, line_columns=[0]):
for i, item in enumerate(tree):
current_line = u""
for j, pos in enumerate(line_columns):
current_line += (pos - j) * " " + "|"
print current_line
if isinstance(item, list):
print current_line[:-1] + "+---> " + item[0]
new_line_columns = line_columns + [line_columns[-1] + 6 + len(item[0]) // 2]
if i == len(tree) - 1:
del new_line_columns[-2]
print_tree(item[1], new_line_columns)
elif isinstance(item, basestring):
print current_line[:-1] + "+---> " + item

Tschö,
Torsten.
 
M

Martin Skou

Torsten said:
It doesn't show Paul and Mary on the same level. I (think I) solved
the problem with this:

I could do so if Poul was in a list of his own, like "Arthur" and "Clara".

/Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top