Write and read a weighted graph to/from a CVS file
Source code name: "graph5_cvs.py"
Programming language: Python
Topic: Data mining/Graphs
DMelt Version 1.4. Last modified: 06/15/1971. License: Pro
https://datamelt.org/code/cache/graph5_cvs_4073.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.


from jhplot import *

g=HGraph().buildWeightedPseudograph()
v1,v2,v3 = "v1","v2","v3"
g.addVertex(v1), g.addVertex(v2), g.addVertex(v3) 

factory = g.getEdgeFactory()
e = factory.createEdge(v1,v2)
g.setEdgeWeight(e, 5) 
g.addEdge(v1, v2, e)

e = factory.createEdge(v2,v3)
g.setEdgeWeight(e, 8.8)
g.addEdge(v2, v3, e)

e = factory.createEdge(v2,v1)
g.setEdgeWeight(e, 0.1)
g.addEdge(v2, v1, e)

HGraph().showGraph(g) # show the graph in GUI 

name='csvfile.csv'
# write to CVS with weights
with open(name,'wb') as file:
    for e in g.edgeSet():
        line=str(g.getEdgeSource(e))+","+str(g.getEdgeTarget(e))+","+str(g.getEdgeWeight(e))
        file.write(line)
        file.write('\n')


# reading from CVS
gg=HGraph().buildWeightedPseudograph()
vertex=set()
graph=[]
with open(name) as f:
  alist = f.read().splitlines()
  for l in alist:
     words = l.split(',')
     v1,v2=str(words[0]),str(words[1]) 
     vertex.add(v1)
     vertex.add(v2)
     w=float(words[2])
     graph.append([v1,v2,w])

# add vertex
for v in vertex:
    gg.addVertex(v)
for j in graph:
    v1,v2,w=j[0],j[1],j[2] 
    e = factory.createEdge(v1,v2)
    gg.setEdgeWeight(e, w)
    gg.addEdge(v1, v2, e)
print "New graph was created from file ",name
HGraph().showGraph(gg) # show the graph in GUI 


You see the box below because you did not login.