【问题标题】:Python How to Create 4 by 4 Matrices Using text FilePython 如何使用文本文件创建 4 x 4 矩阵
【发布时间】:2020-03-18 20:21:27
【问题描述】:

所以我有一个“txt”文件,我想用它创建 4 x 4 矩阵。我需要将它们与每个 “4 4”。我该怎么做? “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

就像我说的,我必须制作单独的矩阵,每个矩阵都以“4 4”结尾。我怎样才能把它们从那里分开?我尝试使用一些方法,但仍然无法做到。感谢您花时间阅读这个问题。我试过这个:

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

输出是这样的:

[[],
 ['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']]

如您所见,这并不是我想要的。

【问题讨论】:

  • 你应该展示你已经尝试过的东西,这样人们就可以用它来指导你,而不是仅仅给你答案。
  • 此外,至少在您的示例中,您的矩阵中有一个 4 4 4 4 行,这使得拆分文本更加困难。在任何情况下,您会从矩阵中获得与矩阵中的数字相同的分隔符?
  • @JuanC 是的,这就是我坚持的部分:(
  • @Andrew 已更新,感谢您的评论 :)

标签: python python-3.x numpy matrix split


【解决方案1】:

您可以从删除这些困扰您的行开始:

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

然后创建矩阵,每个块连续 4 行:

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

【讨论】:

  • 文件名应该放在哪里?我试图替换“text_file.splitlines()”中的“text_file”,但它给了我一个错误cannot reshape array of size 0 into shape (4,4)
  • 如果你事先做text_file = open("input.txt", "r")会怎么样?
  • "_io.TextIOWrapper' object has no attribute "splitlines" 将此视为错误 :( 感谢您帮助我,我会努力解决的!我正在使用 Jupyter Notebook 顺便说一句
【解决方案2】:

另一个例子:

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)]

【讨论】:

  • 优雅!在我看来,空间分割确实比处理字符串更干净。
  • 这也很好用!感谢您提供出色的解决方案:)
【解决方案3】:

这有点过头了,但我正在学习,所以我想使用这个问题来使用Context Manager 发布解决方案。 (也就是说你可以使用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)]

如果您的 python 文件中有上述类,则可以使用以下内容打开文件类型:

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

其中matrix_list 是您的numpy.array 对象列表。像这样使用它只是意味着处理文件的代码被推入类(有效隐藏)。此外,一旦您退出 with 缩进,该文件将关闭。

如果您需要处理大量此类文件,这将特别有用!

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2018-11-11
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多