如何使用文本文件中的 networkx 创建图形?
how to create graph using networkx from text file?
我有一个这样的文本文件:
node1 node2 weight
1 2 3
1 4 4
3 6 1
3 7 5
....
....
我想使用 networkx 创建一个有向图,然后计算每个节点的度数和权重。
import networkx as net
import urllib
import csv
g = net.Graph()
f1 = csv.reader(open("graphdata.txt","rb"))
for x,y,z in f1:
g.add_nodes_from(x,y,z)
报错。任何人都可以帮助我如何构建图形计算每个节点的权重和度数?
您要做的第一件事是注释文件中的任何描述性数据。默认情况下,Networkx 将任何以 # 开头的行视为注释。
# node1 node2 weight
1 2 3
...
import networkx as net
FielName="GraphData.txt"
Graphtype=net.DiGraph() # use net.Graph() for undirected graph
# How to read from a file. Note: if your egde weights are int,
# change float to int.
G = net.read_edgelist(
FielName,
create_using=Graphtype,
nodetype=int,
data=(('weight',float),)
)
# Find the total number of degree, in_degree and out_degree for each node
for x in G.nodes():
print(
"Node: ", x, " has total #degree: ",G.degree(x),
" , In_degree: ", G.out_degree(x),
" and out_degree: ", G.in_degree(x)
)
# Find the weight for each node
for u,v in G.edges():
print ("Weight of Edge ("+str(u)+","+str(v)+")", G.get_edge_data(u,v))
我推荐你阅读Reading and writing graphs in Networkx and have a look to read_edgelist
我有一个这样的文本文件:
node1 node2 weight
1 2 3
1 4 4
3 6 1
3 7 5
....
....
我想使用 networkx 创建一个有向图,然后计算每个节点的度数和权重。
import networkx as net
import urllib
import csv
g = net.Graph()
f1 = csv.reader(open("graphdata.txt","rb"))
for x,y,z in f1:
g.add_nodes_from(x,y,z)
报错。任何人都可以帮助我如何构建图形计算每个节点的权重和度数?
您要做的第一件事是注释文件中的任何描述性数据。默认情况下,Networkx 将任何以 # 开头的行视为注释。
# node1 node2 weight
1 2 3
...
import networkx as net
FielName="GraphData.txt"
Graphtype=net.DiGraph() # use net.Graph() for undirected graph
# How to read from a file. Note: if your egde weights are int,
# change float to int.
G = net.read_edgelist(
FielName,
create_using=Graphtype,
nodetype=int,
data=(('weight',float),)
)
# Find the total number of degree, in_degree and out_degree for each node
for x in G.nodes():
print(
"Node: ", x, " has total #degree: ",G.degree(x),
" , In_degree: ", G.out_degree(x),
" and out_degree: ", G.in_degree(x)
)
# Find the weight for each node
for u,v in G.edges():
print ("Weight of Edge ("+str(u)+","+str(v)+")", G.get_edge_data(u,v))
我推荐你阅读Reading and writing graphs in Networkx and have a look to read_edgelist