Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save koorukuroo/11624720bf6ee3b6955c to your computer and use it in GitHub Desktop.

Select an option

Save koorukuroo/11624720bf6ee3b6955c to your computer and use it in GitHub Desktop.
def read_gdf(path,directed = False):
if directed:
G = nx.DiGraph()
else:
G = nx.Graph()
state = None
nodes = []
edges = []
for line in open(path,'r'):
line = line.rstrip()
if line[0:8] == 'nodedef>':
state = 'nodes'
nodeattr = [x.split()[0] for x in line[8:].split(',')]
elif line[0:8]== 'edgedef>':
state = 'edges'
edgeattr = [x.split()[0] for x in line[8:].split(',')]
else:
if state == 'nodes':
nodes.append(line.split(','))
elif state == 'edges':
edges.append(line.split(','))
else:
print 'Unused line!'
for n in nodes:
G.add_node(n[0])
for idx,extradata in enumerate(n[1:]):
G.node[n[0]][nodeattr[idx+1]]=extradata
for e in edges:
G.add_edge(e[0],e[1])
for idx,extradata in enumerate(e[2:]):
G.node[e[0]][e[1]][nodeattr[idx+2]]=extradata
return G
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment