Programmer Fresco
Programmer Fresco

Reputation: 11

How to read data from file for NetworkX graph

I am having issues trying to read in the following data from a file into NetworkX to build a graph.

Example Data:

The pipe '|' separates the source node (user) from the destination nodes (users). As an example entry:

s1|d1,d2,d3

means that there is an edge between user s1 and user d1, and there is also an edge between user s1 and user d2, etc.

Upvotes: 1

Views: 418

Answers (1)

abc
abc

Reputation: 11949

You can use str.split() to split the lines and parse accordingly. Example:

G = nx.Graph()
with open('g.txt') as f:
   for line in f:
      u, destinations = line.split('|')
         for v in destinations.split(','):
            G.add_edge(u,v)

Upvotes: 1

Related Questions