使用Python将Text文件转换为JSON格式

时间:2016-09-14 04:44:10

标签: python json

我不是编程新手但不擅长python数据结构。我想知道一种使用python将文本文件转换为JSON格式的方法,因为我听说使用python,使用名为import.json的模块,任务更容易。

该文件看起来像

  Source    Target  Value
B cells Streptococcus pneumoniae    226
B cells Candida albicans    136
B cells Mycoplasma  120

对于第一行" B细胞"是来源,目标是"肺炎链球菌"价值是" 226"。我刚开始使用代码,但无法完成它。请帮忙

import json
prot2_names = {}
tmpfil = open("file.txt", "r");
for lin in tmpfil.readlines():
    flds = lin.rstrip().split("\t")
    prot2_names[flds[0]] = "\"" + flds[1] + "\""
    print prot2_names+"\t",
tmpfil.close()

希望输出像

{
  "nodes": [
    {
      "name": "B cells"
    },
    {
      "name": "Streptococcus pneumoniae"
    },
    {
      "name": "Candida albicans"
    },
    {
      "name": "Mycoplasma"
    },
    {
    "links": [
    {
      "source": 0,
      "target": 1,
      "value": "226"
    },
    {
      "source": 0,
      "target": 2,
      "value": "136"
    },
    {
      "source": 0,
      "target": 3,
      "value": "120"
        }
  ]
}

1 个答案:

答案 0 :(得分:1)

您可以将其作为csv文件阅读,并将其转换为json。但是,在将空格用作分隔符时要小心空格,应谨慎处理带空格的值。否则,如果可能,请使用分隔符,而不是space

您正在尝试的工作代码,

import csv
import json

with open('file.txt', 'rb') as csvfile:
    filereader = csv.reader(csvfile, delimiter=' ')
    i = 0
    header = []
    out_data = []
    for row in filereader:
        row = [elem for elem in row if elem]
        if i == 0:
            i += 1
            header = row
        else:
            row[0:2] = [row[0]+" "+row[1]]
            _dict = {}
            for elem, header_elem in zip(row, header):
                _dict[header_elem] = elem
            out_data.append(_dict)

print json.dumps(out_data)

输出,

[
   {
      "Source":"B cells",
      "Target":"Streptococcus",
      "Value":"pneumoniae"
   },
   {
      "Source":"B cells",
      "Target":"Candida",
      "Value":"albicans"
   },
   {
      "Source":"B cells",
      "Target":"Mycoplasma",
      "Value":"120"
   },
   {
      "Source":"B cells",
      "Target":"Neisseria",
      "Value":"111"
   },
   {
      "Source":"B cells",
      "Target":"Pseudomonas",
      "Value":"aeruginosa"
   }
]

更新:刚刚注意到您需要的json样本的更新问题。希望,您可以使用我编写的上述示例来构建它。