2016-09-14 78 views
1

我對編程並不陌生,但不擅長Python數據結構。我想知道一種使用python將文本文件轉換爲JSON格式的方法,因爲我聽說使用python,通過一個名爲import.json的模塊,該任務變得更容易。使用Python將文本文件轉換爲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" 
     } 
    ] 
} 
+0

你有沒有試過用手先做? –

+0

你想讓JSON輸出看起來像什麼?其基本思想是將輸入文件解析爲Python列表和字典的層次結構,然後調用json.dumps(頂級列表或字典)來生成一串JSON。 –

+0

如果你不使用它,你爲什麼要導入'json'? –

回答

0

你可以閱讀它作爲一個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" 
    } 
] 

UPDATE:與您需要json樣品只注意到你的問題更新。希望,你可以用我寫的上面的例子來構建它。

相關問題