Question

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.

Was it helpful?

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

OTHER TIPS

You can do it with the graphviz python library. To install it you just need to launch:

pip install graphviz

and then in Python you can do:

from graphviz import Source

text_from_file = str()
with open('graphviz_dot_file.txt') as file:
    text_from_file = file.read()

src = Source(text_from_file)
src.render(test.gv', view=True ) 

You can find more informations in the Graphviz's manual

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top