如何自动将文本文件转换为graphviz点文件? [英] How to convert text file automatically to graphviz dot file?

查看:271
本文介绍了如何自动将文本文件转换为graphviz点文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想借助graphviz自动将我的文本文件转换为无向图。文本文件由以下代码组成:

  0 

A
关系
B
A
关系
C
B
关系
C
1

0

A
关系
C

B
关系
C
1

这里A,B和C是节点。我可能需要一个或多个图表。 0和1表示每个图的开始和结束。关系数量也可能有所不同。我试着继续sed,但迷路了。我应该如何继续获取我需要的图表?感谢您的帮助。

解决方案

我自己不使用PyGraphViz,但在Python中进行文本处理很简单。给定问题中的输入文件,我称之为 gra1.txt ,以及一个Python文件 gr.py 如下所示:

  import sys,subprocess 

count = 0
for sys in sys .stdin:
if line [0] =='0':
outf =g%d%(count)
g =graph G%d {\\\
%(计数)
count + = 1
elif line [0] =='1':
g + =} \\\

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:
传递
else:
first = line.rstrip()
rel = sys.stdin。 readline()
last = sys.stdin.readline()。rstrip()
g + =%s - %s\\\
%(first,last)

...命令 python gra1.py< gra1.txt 生成输出:

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

图G1 {
A - C
B - C
}

...以及文件 g0.jpg





...和 g1.jpg


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.

解决方案

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:

这篇关于如何自动将文本文件转换为graphviz点文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆