How to read a graph which is a bipartite graph represented in a tab separated format using networkx?

StackOverflow https://stackoverflow.com/questions/22702592

  •  22-06-2023
  •  | 
  •  

Question

The graph question is a graph of movie and their tropes and is in the following format

movie1    trope1    trope2    trope3...etc
movie2    trope1    trope2    trope3...etc
Was it helpful?

Solution

There is probably a more pythonic way to do this:

In [36]:
# create a string from your sample data
import io
temp = """movie1    trope1    trope2    trope3
movie2    trope1    trope2    trope3"""

temp
Out[36]:
'movie1    trope1    trope2    trope3\nmovie2    trope1    trope2    trope3'

In [145]:
# now read it as a csv
import csv
reader=csv.reader(io.StringIO(temp),delimiter=' ',skipinitialspace=True)
# consruct an edge list from the reader object
d=[]
# for each row we want to append to the list a tuple for each movie-trope pair
for row in reader:
    for val in row[1:]:
        d.append((row[0],val))
d

Out[145]:
[('movie1', 'trope1'),
 ('movie1', 'trope2'),
 ('movie1', 'trope3'),
 ('movie2', 'trope1'),
 ('movie2', 'trope2'),
 ('movie2', 'trope3')]

In [143]:
# construct the DiGraph from this edge list
G=nx.DiGraph()
G.add_edges_from(d)
G.edges()
Out[143]:
[('movie1', 'trope1'),
 ('movie1', 'trope2'),
 ('movie1', 'trope3'),
 ('movie2', 'trope1'),
 ('movie2', 'trope2'),
 ('movie2', 'trope3')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top