[英]Python How to Create 4 by 4 Matrices Using text File
所以我有一个“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']]
如您所见,这不是我想要的确切内容。
您可以先删除这些困扰您的行:
>>> 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]])]
再举一个例子:
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)]
这有点过分,但我正在学习,所以我想用这个问题来发布一个使用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
缩进。
如果您需要处理大量此类文件,这将特别有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.