将文件解析为JSON fi的父/子格式

2024-05-18 17:42:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一些关于如何为Gene ontology (.obo)解析此文件的帮助/建议

我在D3中创建一个可视化,需要创建一个JSON格式的“树”文件-

{
 "name": "flare",
 "description": "flare",
 "children": [
  {
   "name": "analytic",
   "description": "analytics",
   "children": [
    {
     "name": "cluster",
     "description": "cluster",
     "children": [
      {"name": "Agglomer", "description": "AgglomerativeCluster", "size": 3938},
      {"name": "Communit", "description": "CommunityStructure", "size": 3812},
      {"name": "Hierarch", "description": "HierarchicalCluster", "size": 6714},
      {"name": "MergeEdg", "description": "MergeEdge", "size": 743}
     ]
    }, etc..

在python的字典中,这种格式似乎相当容易复制,每个条目有3个字段:name、description和children[]。在

我的问题是如何提取数据。上面链接的文件的“对象”结构如下:

^{pr2}$

我需要id,is_a和name字段。我尝试过使用python来解析它,但是我似乎找不到找到每个对象的方法。在

有什么想法吗?在


Tags: 文件对象namesize可视化格式description建议
1条回答
网友
1楼 · 发布于 2024-05-18 17:42:59

这里有一个相当简单的方法来解析.obo文件中的对象。它将对象数据保存到dict中,其中id为键,name和{}数据保存在列表中。然后它使用标准的json模块的.dumps函数漂亮地打印它。在

出于测试目的,我在您的链接中使用了该文件的截断版本,它最多只包含id: GO:0000006。在

此代码忽略包含is_obsolete字段的任何对象。它还删除了is_a字段中的描述信息;我想您可能希望这样做,但是很容易禁用该功能。在

#!/usr/bin/env python

''' Parse object data from a .obo file

    From http://stackoverflow.com/q/32989776/4014959

    Written by PM 2Ring 2015.10.07
'''

from __future__ import print_function, division

import json
from collections import defaultdict

fname = "go-basic.obo"
term_head = "[Term]"

#Keep the desired object data here
all_objects = {}

def add_object(d):
    #print(json.dumps(d, indent = 4) + '\n')
    #Ignore obsolete objects
    if "is_obsolete" in d:
        return

    #Gather desired data into a single list,
    # and store it in the main all_objects dict
    key = d["id"][0]
    is_a = d["is_a"]
    #Remove the next line if you want to keep the is_a description info
    is_a = [s.partition(' ! ')[0] for s in is_a]
    all_objects[key] = d["name"] + is_a


#A temporary dict to hold object data
current = defaultdict(list)

with open(fname) as f:
    #Skip header data
    for line in f:
        if line.rstrip() == term_head:
            break

    for line in f:
        line = line.rstrip()
        if not line:
            #ignore blank lines
            continue
        if line == term_head:
            #end of term
            add_object(current)
            current = defaultdict(list)
        else:
            #accumulate object data into current
            key, _, val = line.partition(": ")
            current[key].append(val)

if current:
    add_object(current)    

print("\nall_objects =")
print(json.dumps(all_objects, indent = 4, sort_keys=True))

输出

^{pr2}$

相关问题 更多 >

    热门问题