Search code examples
graphgraphviztext-manipulationpygraphviz

How to convert text file automatically to graphviz dot file?


I am trying to convert my text file to an undirected graph automatically with the help of graphviz. The text file consists of the following code:

0

A
Relation
B
A
Relation
C
B
Relation
C
1

0

A
Relation
C

B
Relation
C
1

Here A, B and C are nodes. I may require a single or multiple graphs. 0 and 1 represent the start and end of each graph. The number of relations may also vary. I tried to proceed with sed, but got lost. How should I proceed to get the graph I require? Thanks for your help.


Solution

  • I don't use PyGraphViz myself, but doing the text processing in Python is easy enough. Given the input file in the question, which I've called gra1.txt, and a Python file gr.py as follows:

    import sys, subprocess
    
    count = 0
    for line in sys.stdin:
        if line[0] == '0':
            outf = "g%d" % (count)
            g = "graph G%d {\n" % (count)
            count += 1
        elif line[0] == '1':
            g += "}\n"
            dot = subprocess.Popen(["dot", "-Tjpg", "-o%s.jpg" % outf], 
                    stdin=subprocess.PIPE,universal_newlines=True)
            print (g)
            dot.communicate(g)  
        elif len(line.rstrip()) == 0:
            pass
        else:
            first = line.rstrip()
            rel = sys.stdin.readline()
            last = sys.stdin.readline().rstrip()
            g += "%s -- %s\n" % (first,last)
    

    ... the command python gra1.py <gra1.txt produces the output:

    $ python gra1.py <gra1.txt
    graph G0 {
    A -- B
    A -- C
    B -- C
    }
    
    graph G1 {
    A -- C
    B -- C
    }
    

    ... along with the files g0.jpg:

    enter image description here

    ... and g1.jpg:

    enter image description here