解析特定单词后的文本文件

2024-05-26 11:11:39 发布

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

我想解析以下文件并获取“ID”和“Label”后面的值:

{"data" : [{
    "id" : "3743",
    "fgColor" : "#000000",
    "Comment" : [ "GLIO" ],
    "Group" : "0",
    "Shape" : "roundrectangle",
    "GraphicsName" : "TITLE:Glioma",
    "Matching_Attribute" : [ "TITLE:Glioma" ],
    "Entry_id" : "78",
    "Label" : "TITLE:Glioma",
    "EntrezIDs" : "05214, ",
    "shared_name" : "path:hsa05214",
    "Type" : "map",
    "kegg_x" : "86.0",
    "kegg_y" : "58.0",
    "bgColor" : "#FFFFFF",
    "name" : "path:hsa05214",
    "SUID" : 3743,
    "Height" : "25",
    "Width" : "92",
    "Link" : "http://www.kegg.jp/dbget-bin/www_bget?hsa05214",
    "selected" : false
  }]}

我使用的代码如下:没有任何内容写入指定的文件:

import re
cyjs = open("/users/skylake/desktop/cyjs-example.txt", "r")
jsonfile = open("/users/skylake/desktop/jsonfile.txt", "w")
for line in cyjs:
    if line.startswith('"id"'):
        print(line)
        jsonfile.write(line)
jsonfile.close()

Tags: 文件pathnameidtitlewwwlineopen
1条回答
网友
1楼 · 发布于 2024-05-26 11:11:39

有一个更适合的问题工具。你知道吗

它是一个JSON文件,可以用^{} built-in module解析:

In [1]: import json

In [2]: with open("data.txt", "r") as f:
   ...:     data = json.load(f) 

In [3]: obj = data["data"][0]

In [4]: obj["id"]
Out[4]: u'3743'

In [5]: obj["Label"]
Out[5]: u'TITLE:Glioma'

相关问题 更多 >