// I have a text file include
node1 node2 weight
1 2 3
1 4 4
3 6 1
3 7 5
....
....
I want to creat
The first thing you have to do is to comment any descriptive data in your file. By default, Networkx considers any line starting with # as a comment.
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))
I recommend you to read the Reading and writing graphs in Networkx and have a look to read_edgelist