Beta
Beta

Reputation: 1756

Reading Text File of Graph data using NetworkX

I'm very new to networkX. So having problem in very basic things.

I've network data in the text file in following format:

InNode  OutNode

 N1       N5
 N2       N4
 N3       N6
 N2       N2
 N4       N7

My questions are the following:

1) How to read the data using networkX, so that I can get the nodes and edges between the graph?

2) How to calculate the self-edge of the network (N2, N2)?

I tried the following code. But it's not giving me the right answer.

import matplotlib
import networkx as net
import urllib
import csv


g = net.Graph()

f1 = csv.reader(open("data.txt","rb"))

for row in f1: 
    g.add_nodes_from(row)

len(g)

g.number_of_nodes()

Upvotes: 8

Views: 20147

Answers (1)

Beta
Beta

Reputation: 1756

Please find the solution. This might help someone like me:

# Reading the file. "DiGraph" is telling to reading the data with node-node. "nodetype" will identify whether the node is number or string or any other type.


g = nx.read_edgelist("data.txt",create_using=nx.DiGraph(), nodetype = int)

# check if the data has been read properly or not.

nx.info(g)

# count the number of nodes

g.number_of_nodes()

# number of self-nodes

g.selfloop_edges()

Upvotes: 12

Related Questions