How to parse a DOT file in Python

前端 未结 6 2274
别跟我提以往
别跟我提以往 2020-12-15 00:11

I have a transducer saved in the form of a DOT file. I can see a graphical representation of the graphs using gvedit, but what if I want to convert the DOT file to an execut

相关标签:
6条回答
  • 2020-12-15 00:34

    You could start by loading the file using https://code.google.com/p/pydot/ . From there it should be relatively simply to write the code to traverse the in-memory graph according to an input string.

    0 讨论(0)
  • 2020-12-15 00:40

    Another path, and a simple way of finding cycles in a dot file:

    import pygraphviz as pgv
    import networkx as nx
    
    gv = pgv.AGraph('my.dot', strict=False, directed=True)
    G = nx.DiGraph(gv)
    
    cycles = nx.simple_cycles(G)
    for cycle in cycles:
        print(cycle)
    
    0 讨论(0)
  • 2020-12-15 00:44

    I haven’t tried it yet with the sample above, but NetworkX has a read_dot function that might have been a good way to solve this by converting the file into a graph object with good abilities to then analyze and test the graph.

    0 讨论(0)
  • 2020-12-15 00:57

    Install the graphviz library. Then try the following:

    import graphviz
    graphviz.Source.from_file('graph4.dot')
    
    0 讨论(0)
  • 2020-12-15 00:57

    Use this to load a .dot file in python:

    graph = pydot.graph_from_dot_file(apath)
    
    # SHOW as an image
    import tempfile, Image
    fout = tempfile.NamedTemporaryFile(suffix=".png")
    graph.write(fout.name,format="png")
    Image.open(fout.name).show()
    
    0 讨论(0)
  • 2020-12-15 00:58

    Guillaume's answer is sufficient to render the graph in Spyder (3.3.2), which might solve some folks problems.

    If you really need to manipulate the graph, as the OP needs to, it will be a bit complex. Part of the problem is that Graphviz is a graph rendering library, while you are trying to analyse the graph. What you are trying to do is similar to reverse engineering a Word or LateX document from a PDF file.

    If you can assume the nice structure of the OP's example, then regular expressions work. An aphorism I like is that if you solve a problem with regular expressions, now you have two problems. Nonetheless, that might just be the most practical thing to do for these cases.

    Here are expressions to capture:

    • your node information: r"node.*?=(\w+).*?\s(\d+)". The capture groups are the kind and the node label.
    • your edge information: r"(\d+).*?(\d+).*?\"(.+?)\s". The capture groups are source, sink, and the edge label.

    To try them out easily see https://regex101.com/r/3UKKwV/1/ and https://regex101.com/r/Hgctkp/2/.

    0 讨论(0)
提交回复
热议问题