2014-02-24 85 views
0

我是編程和python的新手。所以我面臨很多問題。我需要一些幫助來閱讀python中的文本文件。如何從Python中的文本文件讀取兩個數組或矩陣?

在我的輸入文本文件中,我有兩個包含一些字符串的數據數組。

HEAD1 
1 0 0 
2 3 4 
3 3 0 
END1 

HEAD2 
2 3 4 
8 7 5 
1 0 7 
END2 

現在我想Python讀取這個文件,並將這兩個數組存儲爲2個數組或2個矩陣。數組大小不固定,可以是任何大小。 Python必須根據頭部和尾部來決定大小。我該怎麼做?

我試過numpy.loadtxt和numpy.getfromtxt.In numpy.getfromtxt,我得到了錯誤的字符串。如果沒有字符串,它會將這2個數組分成1個數組。

這裏是試圖這樣做,但不能做到這一點....

import math as m 
import numpy as np 

file_name=input("Input file name(with extension):") 
file=open(file_name,'r') 

line=file.readline() 
while line!= '': 
    print(line,end='') 
    line=file.readline() 

##table=np.loadtxt(file_name) 
##print('table=') 
##print(table) 
## 
table2=np.genfromtxt(file_name,comments='#') 
print('table2=') 
print(table2) 
+2

你可以顯示你嘗試過什麼一些代碼? – zmo

+0

像zmo說,你可以告訴我們你的嘗試? –

回答

5

由於這種格式與「HEAD」和「END」不numpy.loadtxt知道一下,我想你一定有以「塊」這些陣列自己:

import numpy as np 

def tokenizer(fname): 
    with open(fname) as f: 
     chunk = [] 
     for line in f: 
      if 'HEAD'in line: 
       continue 
      if 'END' in line: 
       yield chunk 
       chunk = [] 
       continue 
      chunk.append(line) 


arrays = [np.loadtxt(A) for A in tokenizer('yourfile.txt')] 
+0

爲什麼選擇downvoted? – wim

+0

對不起,我的不好,我誤解了這個問題,我認爲你的回答是不正確的。做了一個虛擬的編輯和upvoted。 :-) –

0

OK ....閱讀兩個數組我不得不改變輸入文件一點點。我在每個數組前添加了一個字符串列。我必須這樣做才能讓Python知道這是兩個不同的數組。這裏是輸入文本文件:

*HEAD1 
    N 1 0 0 
    N 2 3 4 
    N 3 3 0 
    ***** 
    *HEAD2 
    E 2 3 4 
    E 8 7 5 
    E 1 0 7 
    ***** 

我們讀我寫了下面的代碼的文本文件,這兩個數組:

import numpy as np 

file_name=input("Input file name(with extension):") 

# read the input file 

with open(file_name) as f: 
    lines1 = (line for line in f if line.startswith('N')) 
    n_table = np.loadtxt(lines1, comments='*',usecols=(1,2,3)) 
    print('n_table=') 
    print(n_table) 

with open(file_name) as f: 
    lines2=(line for line in f if line.startswith('E')) 
    e_table = np.loadtxt(lines2,comments='*',usecols=(1,2,3,4,5)) 
    print('e_table=') 
    print(e_table) 
相關問題