2014-02-13 96 views
2

我使用的解析器,從文本文件中讀取並返回這樣的類型的字典:複製類型的字典到一個新的字典,蟒蛇

{'m/z array': array([ 345.1, 370.2, 460.2, 1673.3, 1674. , 1675.3]), 
'charge array': array([ 3, 2, 1, 1, 1, 1]), 
'params': {'username': 'Lou Scene', 'useremail': '[email protected]', 
'mods': 'Carbamidomethyl (C)', 'itolu': 'Da', 'title': 'Spectrum 2', 
'rtinseconds': '25', 'itol': '1', 'charge':`enter code here` '2+ and 3+', 
'mass': 'Monoisotopic', 'it_mods': 'Oxidation (M)', 
'pepmass': (1084.9, 1234.0), 
'com': 'Based on http://www.matrixscience.com/help/data_file_help.html', 
'scans': '3'}, 
'intensity array': array([ 237., 128., 108., 1007., 974., 79.])} 

我想讀取整個文件(所有類型的字典)並將它們存儲在一個對象中傳遞給第二個函數,以便腳本不必每次都從文件讀取(這非常緩慢)。我希望保留數據的原始結構,同時傳遞數據以便於訪問。做這個的最好方式是什麼?

我嘗試使用下面的代碼:

print ('enter mgf file name') 
mgf_file = str(raw_input()) 
from pyteomics import mgf 
reader = [] 
with mgf.read(mgf_file) as temp_read: 
    for things in temp_read: 
     reader.update(things) 


compo_reader(reader) 
+0

你在使用什麼語法分析器?使用它的代碼是什麼樣的? – abarnert

+0

您仍然需要向我們展示您的代碼,而不是讓我們閱讀文檔並嘗試猜測您可能使用該庫編寫的代碼。請參閱[MCVE](http://stackoverflow.com/help/mcve)獲取更多幫助,以獲取更好的問題。 – abarnert

+1

對不起!我是這個網站和編程的新手,仍在學習如何正確執行此操作。我編輯了我原來的帖子。感謝您的迴應。 – kkhatri99

回答

2

只需將它們放在一個列表,並通過周圍的名單。

由於您沒有向我們展示您的代碼,因此我無法告訴您如何更改它,但我可以向您展示一些假代碼。

假設您有一個功能parser(f),它讀取f中的一行,並返回顯示給我們的那些字典中的一個,或返回其中的一個字典,或返回None。所以:

with open(filename, 'rb') as f: 
    things = [] 
    while True: 
     thing = parser(f) 
     if not thing: 
      break 
     things.append(thing) 

或者,更簡潔:

with open(filename, 'rb') as f: 
    things = list(iter(partial(parser, f), None)) 

如果您正在使用的解析器這已經是一個迭代,就像csv.DictReader,那麼它的更簡單:

with open(filename, 'rb') as f: 
    reader = csv.DictReader(f) 
    things = list(reader) 

然而你已經做到了,一旦你有這些字典的列表,你可以通過這個列表,遍歷它,等等。


針對您的特殊的代碼,它看起來像一個mgf.read()對象是在字典的迭代器,就像一個csv.DictReader,所以它應該只是:

with mgf.read(mgf_file) as temp_read: 
    reader = list(temp_read) 

如果這是不正確的,你會要做到這一點:

reader = [] 
with mgf.read(mgf_file) as temp_read: 
    for thing in temp_read: 
     reader.append(thing) 

換句話說,而不是在一個字典一邊喊update每個新字典,只是append每一個到列表中。