2017-08-17 67 views
-5

長的文本文件,我有一個文本文件是這樣的:讀取文本文件在Python

Header... 
40x1 matrix 
# Comment1 
# Comment 2 
36x1 matrix 
# Comment 1 
# Comment 2 
40x 36 matrix 
# Comment 1 
40x 36 matrix 
# Comment 1 
40x 36 matrix 

現在我想通過每個40x36矩陣讀40x1矩陣,分別36x1矩陣和循環。

任何人都可以提供一些幫助嗎?

問候 奧巴馬

+0

你的文件結構如何不是很清楚。你能否詳細說明一下? – Eduardo

+0

[爲什麼「有人可以幫我嗎?」不是一個真正的問題?](http://meta.stackoverflow.com/q/284236) – kazemakase

+0

對不起,這裏是一個文件的例子:https://www.dropbox的.com/S/uu7u87mthur4thn/files.txt?DL = 0 – Barack

回答

1

你有#線作爲基體之間的分離。所以,如果你的文件行,你環線,可以使基質與此#線分開,並建立了他們:

file = open("file.txt", "r") 
lines = file.readlines() 

在這一點上,線是一個列表。線[i]是線n°i + 1作爲一個字符串。

# k, a counter to loop on the lines 
k = 1 
# Matrix_list is a list of the matrix (size i*j) like that [40*1, 36*1, ...] 
Matrix_list = [] 
while k < len(lines): 
    if "#" in lines[k-1] and "#" not in lines[k]: 
     # Start a new matrix 
     row = [] 

     # Loop to get all the lines of the current matrix 
     while "#" not in lines[k]: 

      if k > len(lines): 
       break 

      row.appends(lines[k]) 
      k +=1 

     # At this point, row is a list of every row of your matrix 
     # First we get the matrix size i*j and create a matrix 
     i = len(row) 
     j = len(row[0].split()) 
     Mat = np.zeros((i, j)) 

     row_position = 0 

     for elt in row: 
      colum_position = 0 
      L = elt.split() 
      for data in L: 
       Mat[row_position, colum_position] = data 
       colum_position += 1 
      row_position +=1 

     # Once all the data you had was palced in the matrix : 
     Matrix_list.append(Mat) 

    else: 
     k += 1 

嗯,我希望你能得到算法的想法,但我很確定它不會馬上工作。需要做一些測試和調整,但全球的想法應該做到這一點。最後,你會得到Matrix_list,列表中的每個矩陣都是一個numpy數組。

一旦你有了,你可以做任何你想要的每個矩陣。