Welcome, guest | Sign In | My Account | Store | Cart

This is an easy way to construct a tree by given leaf nodes.

Python, 48 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from xml.dom.minidom import Document

def get_tree_representation_of_loaded_python_modules(self):
        modules = sys.modules.keys()
        modules.sort()

        tree_data = Document()
        node = tree_data.createElement('li')
        text = tree_data.createTextNode('Loaded Python Modules')
        node.appendChild(text)
        tree_data.appendChild(node)
        map = {}
        for module in modules:
            ms = module.split('.')
            path = node
            for level in range(len(ms)):
                nodes = map.get(level)
                if nodes == None:
                    node1 = tree_data.createElement('ul')
                    node2 = tree_data.createElement('li')
                    textNode = tree_data.createTextNode(ms[level])
                    node2.appendChild(textNode)
                    node1.appendChild(node2)
                    path.appendChild(node1)
                    nodes = [node2]
                    map[level] = nodes
                else:
                    node2 = None
                    for tmpNode in nodes:
                        if tmpNode.firstChild.data == ms[level]:
                            node2 = tmpNode
                            node1 = node2.parentNode
                    if node2 == None:
                        node1 = path.childNodes.item(1)
                        if node1==None:
                            node1 = tree_data.createElement('ul')
                            path.appendChild(node1)
                        node2 = tree_data.createElement('li')
                        textNode = tree_data.createTextNode(ms[level])
                        node2.appendChild(textNode)
                        node1.appendChild(node2)
                        nodes += [node2]
                        map[level] = nodes
                path = node2

        str = tree_data.toprettyxml()
        str = str[len('<?xml version="1.0" ?>')+1:]
        return str

Document of xml.dom.minidom is used as tree data keeper.

It can also be used to generate a pretty traversal output after finishing node insertions.

Created by G. C. Lee on Mon, 24 Oct 2005 (PSF)
Python recipes (4591)
G. C. Lee's recipes (1)

Required Modules

Other Information and Tasks