繁体   English   中英

如何在python中将图json文件转换为图邻接列表文件?

[英]How to convert graph json file to graph adjacency list file in python?

我在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"
                }
            },
#! /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" }}
]''')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM