Visualize tree in bash, like the output of unix tree

2024/10/5 1:19:29

Given input:

apple: banana eggplant
banana: cantaloupe durian
eggplant:
fig:

I would like to concatenate it into the format:

├─ apple
│  ├─ banana
│  │   ├─ cantaloupe
│  │   └─ durian
│  └─ eggplant
└─ fig

There may or may not be multiple root elements (in the above example, there are two root elements), and I would like to find a solution that handles them without an issue.

Are there any command line tools that can handle this kind of transformation? Failing that, is there anything in other scripting languages that can handle this somewhat easily (I've looked at Python's pprint but I'm not sure how to use it for something like this either)?

Answer

following code shall produce the tree structure you are asking for:

branch = '├'
pipe = '|'
end = '└'
dash = '─'class Tree(object):def __init__(self, tag):self.tag = tagclass Node(Tree):def __init__(self, tag, *nodes):super(Node, self).__init__(tag)self.nodes = list(nodes)class Leaf(Tree):passdef _draw_tree(tree, level, last=False, sup=[]):def update(left, i):if i < len(left):left[i] = '   'return leftprint ''.join(reduce(update, sup, ['{}  '.format(pipe)] * level)) \+ (end if last else branch) + '{} '.format(dash) \+ str(tree.tag)if isinstance(tree, Node):level += 1for node in tree.nodes[:-1]:_draw_tree(node, level, sup=sup)_draw_tree(tree.nodes[-1], level, True, [level] + sup)def draw_tree(trees):for tree in trees[:-1]:_draw_tree(tree, 0)_draw_tree(trees[-1], 0, True, [0])

it requires you represent the data using given form.


about your data deserialization, you just need to keep track of the parent nodes, such that when a leaf appears to be a node, you just replace it:

class Track(object):def __init__(self, parent, idx):self.parent, self.idx = parent, idxdef parser(text):trees = []tracks = {}for line in text.splitlines():line = line.strip()key, value = map(lambda s: s.strip(), line.split(':', 1))nodes = value.split()if len(nodes):parent = Node(key)for i, node in enumerate(nodes):tracks[node] = Track(parent, i)parent.nodes.append(Leaf(node))curnode = parentif curnode.tag in tracks:t = tracks[curnode.tag]t.parent.nodes[t.idx] = curnodeelse:trees.append(curnode)else:curnode = Leaf(key)if curnode.tag in tracks:# well, how you want to handle it?pass # ignoreelse:trees.append(curnode)return trees

it runs:

>>> text='''apple: banana eggplant
banana: cantaloupe durian
eggplant:
fig:'''
>>> draw_tree(parser(text))
├─ apple
|  ├─ banana
|  |  ├─ cantaloupe
|  |  └─ durian
|  └─ eggplant
└─ fig

hope it fully deals with your problem.


update

my code offers some concern over corner cases, for example:

>>> text='''apple: banana eggplant
banana: cantaloupe durian
eggplant:'''
>>> draw_tree(parser(text))
└─ apple├─ banana|  ├─ cantaloupe|  └─ durian└─ eggplant

notice the left most side of subnodes of apple, there is no | to the end because they are suppressed.

or empty in the middle:

>>> text='''apple: banana
banana: cantaloupe durian
eggplant:'''
>>> draw_tree(parser(text))
├─ apple
|  └─ banana
|     ├─ cantaloupe
|     └─ durian
└─ eggplant
https://en.xdnf.cn/q/70538.html

Related Q&A

pygame.error: Failed loading libmpg123.dll: Attempt to access invalid address

music = pygame.mixer.music.load(not.mp3) pygame.mixer.music.play(loops=-1)when executing the code I got this error: Traceback (most recent call last):File "C:\Users\Admin\AppData\Local\Programs\Py…

Plot Red Channel from 3D Numpy Array

Suppose that we have an RGB image that we have converted it to a Numpy array with the following code:import numpy as np from PIL import Imageimg = Image.open(Peppers.tif) arr = np.array(img) # 256x256x…

How to remove image noise using opencv - python?

I am working with skin images, in recognition of skin blemishes, and due to the presence of noises, mainly by the presence of hairs, this work becomes more complicated.I have an image example in which …

Django groups and permissions

I would like to create 2 groups (Professors, Students). And I would like to restrict students from creating and deleting Courses.views.py:def is_professor(function=None):def _is_professor(u):if user.gr…

How to (properly) use external credentials in an AWS Lambda function?

I have a (extremely basic but perfectly working) AWS lambda function written in Python that however has embedded credentials to connect to: 1) an external web service 2) a DynamoDB table. What the fu…

How to set environment variable TF_Keras = 1 for onnx conversion?

Recently updated to tensorflow 2.0 and am having trouble getting my .h5 models into .onnx . Used to be a very simple procedure but now I am having an issue. When I run the following code:# onnx testing…

Django App Engine: AttributeError: AnonymousUser object has no attribute backend

I am using djangoappengine. When I try create a new user, authenticate that user, and log them in, I get the following error AttributeError: AnonymousUser object has no attribute backend.My code is sim…

python identity dictionary [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError? I need…

Whats a good library to manipulate Apache2 config files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

AttributeError: module object has no attribute webdriver

AttributeError: module object has no attribute webdriverwhy this error happen when write import selenium and when write code like this no error happenfrom selenium import webdriver