Last active
June 1, 2021 02:38
-
-
Save jschaub30/54054f81508003d01d5d to your computer and use it in GitHub Desktop.
Python script for converting graphml (*gml) files to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
def gml_sub(blob): | |
lines = [] | |
for line in blob.split('\n'): | |
line = line.strip() | |
lines.append(line) | |
blob = "\n".join(lines) | |
blob = blob.replace('\n\n', '\n') | |
blob = blob.replace(']\n', '},\n') | |
blob = blob.replace('[\n', '{') | |
blob = blob.replace('\n{', '\n {') | |
for s in ['id', 'label', 'source', 'target', 'value']: | |
blob = blob.replace(s, '"%s":' % s) | |
blob = blob.replace('\n"', ', "') | |
blob = blob.replace('\n}', '}') | |
return blob.strip('\n') | |
def main(graphfile): | |
""" | |
Converts GraphML file to json | |
Usage: | |
>>> python convert.py mygraph.gml | |
""" | |
with open(graphfile, 'r') as f: | |
blob = f.read() | |
blob = ''.join(blob.split('node')[1:]) | |
nodes = blob.split('edge')[0] | |
edges = ''.join(blob.split('edge')[1:]).strip().rstrip(']') | |
nodes = gml_sub(nodes) | |
edges = gml_sub(edges) | |
print '{\n "nodes":[' | |
print nodes.rstrip(',') | |
print ' ],\n "edges":[' | |
print ' ' + edges.rstrip(',') | |
print ' ]\n}\n' | |
if __name__ == '__main__': | |
main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment