2016-10-10 55 views
0

我試圖從csv文件創建圖形工具(https://graph-tool.skewed.de)圖形的內容,如:如何使用CSV工具在Python中創建圖形文件數據?

A,B,50 
A,C,34 
C,D,55 
D,D,80 
A,D,90 
B,D,78 

現在我想創建一個A,B,C,d圖作爲節點和第三列數字作爲邊緣。我正在使用圖形工具庫。第三列數字顯示由A,B和A,C等共享的常用項目。

我可以通過「networkx」(read_edgelist等)來完成,但我想用圖形工具來完成。

+0

一般如何你希望你的程序是什麼? (即,你想繪製任何通過它的CSV文件,還是隻需要這個文件?)你可以發佈你的代碼到目前爲止嗎? –

+0

實際上,我用networkx做了一些代碼,但是我沒有任何圖形工具代碼(我不知道如何開始用圖形工具讀取邊緣) – Nikito

+0

具體來說,你已經有了CSV解析器的工作?即你在內存中是否已經擁有'[[A,B,50],[A,C,50]]? –

回答

1

假設你已經知道如何閱讀Python中的CSV文件(例如,使用CSV library),網站上的文檔explain how to do this very clearly.

喜歡的東西

import graph_tool 
g = Graph(directed=False) 


# this is the result of csv.parse(file) 
list_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]] 

vertices = {} 

for e in list_of_edges: 
    if e[0] not in vertices: 
     vertices[e[0]] = True 
    if e[1] not in vertices: 
     vertices[e[1]] = True 


for d in vertices: 
    vertices[d] = g.add_vertex() 

for edge in list_of_edges: 
    g.add_edge(vertices[edge[0]], vertices[edge[1]]) 
+0

謝謝,我測試過,它的工作,但如果我想在節點而不是索引號顯示標籤呢?我使用這段代碼來繪製圖形:graph_draw(g,vertex_text = g.vertex_index,vertex_font_size = 18, output_size =(800,800),output =「two-nodes.png」) – Nikito

2

您可以使用add_edge_list( )添加邊緣列表。如果存儲的名稱與自動分配的索引不同,則它將返回包含列表中名稱的字符串列表。

例:

from graph_tool.all import * 
import csv 

g=Graph(directed=False) 
csv_E = csv.reader(open('*text_input*')) 

e_weight=g.new_edge_property('float') 
v_names=g.add_edge_list(csv_E,hashed=True,string_vals=True,eprops=[e_weight]) 
#this will assign the weight to the propery map *e_weight* and the names to *v_names* 

graph_draw(g, vertex_text=v_names) 
相關問題