How to convert text file automatically to graphviz dot file?

天大地大妈咪最大 提交于 2019-12-10 23:43:41

问题


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.


回答1:


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:

... and g1.jpg:




回答2:


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



来源:https://stackoverflow.com/questions/21077504/how-to-convert-text-file-automatically-to-graphviz-dot-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!