2014-01-12 121 views
2

我想借助graphviz自動將我的文本文件轉換爲無向圖。該文本文件由以下代碼組成:如何將文本文件自動轉換爲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,但迷路了。我應該如何繼續獲取我需要的圖表?謝謝你的幫助。

+0

你能給出你一個示例中找到更多的信息期望結果圖看起來像?我認爲第二個看起來像'A - C - B',第一個是三角形,A,B和C三角形。 – Simon

+0

是的。第一個包含三個角落的A,B和C.第二個將包含A-C-B,即C與B和A都連接。 – abhisekG

回答

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

enter image description here

...和g1.jpg

enter image description here

+0

它工作!非常感謝您的幫助。 – abhisekG

0

您可以用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

+0

我試圖您的解決方案得到了錯誤, PUN-U531305L001:桌面531305 $蟒蛇graph.py 回溯(最近通話最後一個): 文件 「graph.py」,8號線,在 src.render(」 test.gv',view = True) 文件「/Library/Python/2.7/site-packages/graphviz/files.py」,第226行,在渲染 '在您的系統\'路徑'%cmd) RuntimeError :未能執行['dot','-Tpdf','-O','test.gv'],請確保Graphviz可執行文件位於您系統的路徑上 –

+1

我有類似的問題。這似乎是你在寡婦上使用** Graphviz **。確保你的*系統路徑變量*上有** Graphviz **。這裏[你的解決方案](http://stackoverflow.com/questions/18438997/why-is-pydot-unable-to-find-graphvizs-executables-in-windows-8/20458620#20458620) – RousseauAlexandre