简体   繁体   English

Python 如何使用文本文件创建 4 x 4 矩阵

[英]Python How to Create 4 by 4 Matrices Using text File

So I have a "txt" file and I want to create 4 by 4 matrices with it.所以我有一个“txt”文件,我想用它创建 4 x 4 矩阵。 I need to separate them from each "4 4".我需要将它们与每个“4 4”分开。 How can I do it?我该怎么做? The "input.txt" file contains this: “input.txt”文件包含以下内容:

4 4
55 55 55 56
66 66 66 67
77 77 77 78
88 88 88 89
4 4
1 2 3 4
2 2 2 2
3 3 3 3
4 4 4 4
4 4
11 12 13 14
22 24 24 25
33 34 35 36
44 45 46 47

Just like I said, I have to make individual matrices and the each matrix ends from "4 4".就像我说的,我必须制作单独的矩阵,每个矩阵都以“4 4”结尾。 How can I separate them from there?我怎样才能将它们与那里分开? I tried to use some methods but couldn't do it still.我尝试使用一些方法,但仍然无法做到。 Thank you for spending your time to read this question.I tried this:感谢您花时间阅读这个问题。我试过这个:

[i.lower().replace('4 4', '').split() for i in open('input.txt', 'r')]

The output is this:输出是这样的:

[[],
 ['55', '55', '55', '56'],
 ['66', '66', '66', '67'],
 ['77', '77', '77', '78'],
 ['88', '88', '88', '89'],
 [],
 ['1', '2', '3', '4'],
 ['2', '2', '2', '2'],
 ['3', '3', '3', '3'],
 [],
 [],
 ['11', '12', '13', '14'],
 ['22', '24', '24', '25'],
 ['33', '34', '35', '36'],
 ['45', '46', '47']]

As you can see, it's not the exact thing that I want.如您所见,这不是我想要的确切内容。

You can start by removing these lines that bother you:您可以先删除这些困扰您的行:

>>> lines = [line for line in text_file.splitlines() if line != "4 4"]

Then create matrices with every chunk 4 successive rows:然后用每个块 4 个连续行创建矩阵:

>>> [np.fromstring("\n".join(lines[x:x+4]), sep=" ", dtype=int).reshape(4,4) 
     for x in range(0, len(lines), 4)]

Which output is a list of matrices of size (4, 4):哪个输出是大小为 (4, 4) 的矩阵列表:

[array([[55, 55, 55, 56],
       [66, 66, 66, 67],
       [77, 77, 77, 78],
       [88, 88, 88, 89]]), 

 array([[1, 2, 3, 4],
       [2, 2, 2, 2],
       [3, 3, 3, 3],
       [4, 4, 4, 4]]), 

 array([[11, 12, 13, 14],
       [22, 24, 24, 25],
       [33, 34, 35, 36],
       [44, 45, 46, 47]])]

Just another example:再举一个例子:

f = open('untitled.txt', 'r').read().splitlines()

# filter the '4 4' elements, and split on space
s = list(map(str.split, filter(lambda x: x != '4 4', f)))

# turn the list in to a list of matrices
m = [np.array(s[i:i+4]) for i in range(0, len(s), 4)]

This is a bit over-the-top but I'm learning, so I'd like to use this question to post a solution using a Context Manager .这有点过分,但我正在学习,所以我想用这个问题来发布一个使用Context Manager的解决方案。 (This means you can use with , I'll give an example): (这意味着你可以使用with ,我举个例子):

import numpy as np

class MyMatrixFile(object):
    def __init__(self, filename, mode):
        self.__filename = filename
        self.__mode = mode

    def __enter__(self):
        self.__open_file = open(self.__filename, self.__mode)
        self.__deserialise()
        return self.__myMatrixList

    def __exit__(self, *args):
        self.__open_file.close()

    def __deserialise(self):
        data = self.__open_file.read().splitlines()
        temp = list(map(str.split, filter(lambda x: x != '4 4', data)))
        self.__myMatrixList = [np.array(temp[i:i+4]) for i in range(0, len(temp), 4)]

If you have the above class in your python file, you can open your file types with the following:如果您的 python 文件中有上述类,您可以使用以下命令打开您的文件类型:

with MyMatrixFile('test_matrix_file.txt', 'r') as matrix_list:
    # do stuff

Where matrix_list is your list of numpy.array objects.其中matrix_list是您的numpy.array对象列表。 Using it like this just means the code processing the file is pushed in to the class (effectively hidden).像这样使用它只是意味着处理文件的代码被推送到类中(有效隐藏)。 Additionally, the file will close once you come out of the with indent.此外,一旦你来的出来的文件将关闭with缩进。

This would be especially useful if you need to process lots of this type of file!如果您需要处理大量此类文件,这将特别有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM