[Python] From graph to .dot file python

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a tree represented by this string (this is a decision tree made by scratch): {'index': 1, 'right': {'index': 0, 'right': 'no', 'value': 'overcast', 'left': 'Yes'}, 'value': 'Mild', 'left': {'index': 0, 'right': {'index': 0, 'right': 'Yes', 'value': 'overcast', 'left': 'Yes'}, 'value': 'rain', 'left': {'index': 0, 'right': 'Yes', 'value': 'rain', 'left': 'Yes'}}}

    and I'd like to represent it (with edges and nodes using Graphviz). To print it I use this function in Python:

    def print_tree(node, depth=0):
    filename = outlook.csv'
    dataset = load_csv(filename)
    columns = dataset[0]
    if isinstance(node, dict):

    print('%s[%s = %s]' % ((depth * ' ', (columns[node['index']]), node['value'])))
    print_tree(node['left'], depth+1)
    print_tree(node['right'], depth+1)
    else:
    print('%s[%s]' % ((depth*' ', node)))


    I'd like to use Digraph from GraphViz from graphviz import Digraph

    def createGraph(node):
    dot = Digraph(comment="experiment")
    def graph(node):
    if isinstance(node, dict):
    dot.node(str(id(node)))
    dot.edge(str(id(node)) , str(id(node['right'])))
    graph(node['left'])
    graph(node['right'])
    else:
    dot.node(str(id(node)), str(node))
    dot.render('test-output/roundround5.gv', view=True)
    'test-output/round.gv.pdf'
    graph(node)


    but obviously code is wrong. Can anybody help?

    Continue reading...

Compartilhe esta Página