graph - 如何将文本文件自动转换为graphviz点文件?

标签 graph graphviz text-manipulation pygraphviz

我正在尝试在 graphviz 的帮助下自动将文本文件转换为无向图。该文本文件包含以下代码:

0

A
Relation
B
A
Relation
C
B
Relation
C
1

0

A
Relation
C

B
Relation
C
1

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

最佳答案

我自己不使用 PyGraphViz,但用 Python 进行文本处理很容易。给定问题中的输入文件,我将其称为 gra1.txt ,和一个 Python 文件 gr.py如下:

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)

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

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

graph G1 {
A -- C
B -- C
}

...以及文件 g0.jpg :

enter image description here

...和g1.jpg :

enter image description here

关于graph - 如何将文本文件自动转换为graphviz点文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077504/

相关文章:

javascript - 当 Material 为 MeshPhongMaterial 时,无法为使用 Three.js 绘制的圆环着色

r - 文本替换——模式是一组字符串[r]

git - 如何在一行中获取带有简短统计信息的 Git 日志?

c++ - 使用 Boost Graph Library 和 Bellman-Ford 算法

javascript - 如何用多色线绘制图形

java - 绘制跨多个 View 或面板或水平滚动的 Java 2D 图表

PHP GraphViz 文档

windows - Graphviz:如何从 .dot 到图表?

php - 使用 Image_Graphviz 包设置默认节点属性

ruby - 如何使用另一个字符串在 Ruby 中切掉一个字符串?