在python

时间:2017-08-17 11:54:11

标签: 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矩阵。

有人可以提供一些帮助吗?

此致 美国总统

1 个答案:

答案 0 :(得分:1)

您将#lines作为矩阵之间的分隔。因此,如果您在文件中逐行循环,则可以将矩阵与此#行分开,并构建它们:

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

此时,行是一个列表。 lines [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,这是一个列表,其中包含你的txt文件的每个矩阵作为一个numpy数组。

一旦你拥有了这个,那么你可以用每个矩阵做任何你想做的事。