【问题标题】:How to convert text file automatically to graphviz dot file?如何将文本文件自动转换为 graphviz dot 文件?
【发布时间】:2014-01-31 09:14:38
【问题描述】:

我正在尝试借助 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,但迷路了。我应该如何继续获得我需要的图表?感谢您的帮助。

【问题讨论】:

  • 您能否举例说明您期望生成的图表是什么样的?我认为第二个看起来像 A -- C -- B 并且第一个是三角形,三个角有 A、B 和 C,我是否正确。
  • 是的。第一个将在三个角落包含 A、B 和 C。第二个将包含 A--C--B 即 C 与 B 和 A 都连接。

标签: graph graphviz text-manipulation pygraphviz


【解决方案1】:

您可以使用graphviz python 库来实现。要安装它,您只需要启动:

pip install graphviz

然后在 Python 中你可以这样做:

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 ) 

您可以在Graphviz's manual找到更多信息

【讨论】:

  • 我在尝试您的解决方案时遇到错误,PUN-U531305L001:Desktop 531305$ python graph.py Traceback(最近一次调用最后一次):文件“graph.py”,第 8 行,在 src.render('test.gv', view=True) File "/Library/Python/2.7/site-packages/graphviz/files.py", line 226, in render 'are on your systems\' path' % cmd ) RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test.gv'],确保 Graphviz 可执行文件在您的系统路径上
  • 我遇到了类似的问题。您似乎在 Widows 上使用 Graphviz。确保您的 系统路径变量 上有 Graphviz。这里your solution
【解决方案2】:

我自己不使用 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:

...和g1.jpg:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多