Search code examples
python-2.7networkx

how to create graph using networkx from text file?


I have a text file like this:

node1  node2  weight
1      2      3
1      4      4
3      6      1
3      7      5
....
....

I want to create a directed graph using networkx then count the degree and weight for each node.

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)

It gives an error. Can anybody help me as to how build graph the compute the weight and degree for each node?


Solution

  • 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.

    # 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))
    

    I recommend you to read the Reading and writing graphs in Networkx and have a look to read_edgelist