读取文本文件python中的长文本文件

读取文本文件python中的长文本文件,python,numpy,matrix,Python,Numpy,Matrix,我有这样一个文本文件: 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 现在我想分别读取40x1矩阵,36x1矩阵,并循环遍历每个40x36矩阵 有人能帮忙吗 问候 Barack你有#行作为矩阵之间的分隔。因此,如果您在文件中逐行循环,您可以用这些行分

我有这样一个文本文件:

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
现在我想分别读取
40x1
矩阵,
36x1
矩阵,并循环遍历每个
40x36
矩阵

有人能帮忙吗

问候 Barack

你有#行作为矩阵之间的分隔。因此,如果您在文件中逐行循环,您可以用这些行分隔矩阵,并构建它们:

file = open("file.txt", "r")
lines = file.readlines()
此时,行是一个列表。第[i]行是作为字符串的第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
#k,线路上循环的计数器
k=1
#矩阵_list是矩阵(大小i*j)的列表,如[40*1,36*1,…]
矩阵_列表=[]
当klen(行):
打破
行。附录(行[k])
k+=1
#此时,行是矩阵中每一行的列表
#首先我们得到矩阵大小i*j,然后创建一个矩阵
i=len(世界其他地区)
j=len(第[0]行)。拆分()
Mat=np.零((i,j))
行位置=0
对于第行中的elt:
立柱位置=0
L=elt.split()
对于L中的数据:
Mat[行位置,列位置]=数据
立柱位置+=1
行位置+=1
#在矩阵中填写完所有数据后:
矩阵列表追加(Mat)
其他:
k+=1
嗯,我希望你了解这个算法,尽管我很确定它不会马上起作用。需要做一些测试和调整,但全球理念应该可以做到这一点。最后是矩阵列表,该列表将txt文件中的每个矩阵作为numpy数组


一旦你有了它,你就可以对每个矩阵做任何你想做的事情。

你的文件是如何构造的还不是很清楚。请您详细说明一下好吗?对不起,这里有一个文件示例: