4

我有存储在数据库中的加权边列表。如何轻松地从中创建图表(无需将其写入文件并读取它)

这里是可复制的

import sqlite3 
con = sqlite3.connect(":memory:")

with con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")


cur.execute('SELECT * FROM DATEN')
data = cur.fetchall()

我创建图表的尝试失败:

import networkx as nx
G = nx.Graph()
for x in data:
     x1 = {'source': data[0][0], 'target': data[0][1], 'weight':  data[0][2]} 
     print x1 

     G.add_edge(x1)  # THIS IS NOT WORKING 

有没有更简单的方法来做到这一点?

4

4 回答 4

5

游标是一个迭代器,它在执行 SELECT 语句后产生行。例如,不是将所有结果提取到一个列表中

rows = cur.fetchall()

您可以使用

for row in cur:

但是,由于 NetworkX add_weighted_edges_from方法接受一个迭代器,您可以cur直接传递:

G.add_weighted_edges_from(cur)

这是多态性的一个很好的例子。NetworkX 的设计者不需要做任何特别的事情,甚至不需要预料 sqlite3 游标可能会作为参数传递,他们只需要在假设第一个参数是迭代器的情况下编写代码。


import networkx as nx
import sqlite3 
import matplotlib.pyplot as plt

with sqlite3.connect(":memory:") as con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")

    G = nx.Graph()
    cur.execute('SELECT Source, Target, Weight FROM DATEN')
    G.add_weighted_edges_from(cur)    

nx.draw(G)
plt.show()

在此处输入图像描述

于 2013-04-16T09:26:53.673 回答
0

Graph.add_edge()不以 dict 作为参数,它至少需要两个节点和可选的关键字参数。试试这个:

import networkx as nx
G = nx.Graph()
for x in data:
     G.add_edge(x[0], x[1], weight=x[2])
于 2013-04-16T09:20:51.483 回答
0

首先,你能给我们错误信息吗?

然后,您似乎没有正确使用 add_edge (请参阅:http ://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.add_edge.html#networkx.Graph.add_edge )

你应该尝试像这样添加你的边缘:

import networkx as nx
G = nx.Graph()
for x in data:
    G.add_edge(x[0], x[1], weight=x[2])
于 2013-04-16T09:26:59.520 回答
0

这有效

f=open('G_train.txt','r')
data=f.read()
EDGES=ast.literal_eval(data)

g = nx.DiGraph((x, y, {'weights': v}) for (x, y), v in Counter(EDGES).items())

print("Edges", g.edges(data=True), sep='\n')
于 2019-08-13T04:40:47.460 回答