我有一个像这样的文本文件:
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看看 read_edgelist
关于python-2.7 - 如何使用networkx从文本文件创建图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561944/