我在python中有图形的json文件,我想解析它并将其写为邻接列表文件,如下所示。有人可以帮助我吗?
A B
C A
D Z
其中第一列和第二列是节点。我没有.json文件的经验,这里是我的json文件的图形。
"edges": [
{
"data": {
"cost": 0.01,
"source": "HBA2",
"target": "HBB"
}
},
{
"data": {
"cost": 0.598835,
"source": "HBA2",
"target": "EGFR"
}
},
{
"data": {
"cost": 0.594442,
"source": "HBA2",
"target": "DAXX"
}
},
{
"data": {
"cost": 0.598835,
"source": "HBA2",
"target": "PBK"
}
},
{
"data": {
"cost": 0.598835,
"source": "HBA2",
"target": "MAPK14"
}
},
{
"data": {
"cost": 0.598835,
"source": "HBA2",
"target": "MST4"
}
},
答案 0 :(得分:1)
#! /usr/bin/env python3
import json
def get_edges(graph):
for d in json.loads(graph):
node = d['data']
yield node['source'], node['target']
def plot(graph, outfile='graph.txt'):
with open(outfile, 'w') as fout:
for src, dst in get_edges(graph):
fout.write('%s %s\n' % (src, dst))
if __name__ == '__main__':
plot('''
[ { "data": { "cost": 0.010000, "source": "HBA2", "target": "HBB" }},
{ "data": { "cost": 0.598835, "source": "HBA2", "target": "EGFR" }},
{ "data": { "cost": 0.594442, "source": "HBA2", "target": "DAXX" }},
{ "data": { "cost": 0.598835, "source": "HBA2", "target": "PBK" }},
{ "data": { "cost": 0.598835, "source": "HBA2", "target": "MAPK14" }},
{ "data": { "cost": 0.598835, "source": "HBA2", "target": "MST4" }}
]''')