简体   繁体   English

从.txt 文件重塑矩阵

[英]Reshape matrix from .txt file

I have this code that takes an .txt that has integers in the following format:我有这个代码,它需要一个具有以下格式的整数的.txt

3 7 12  90 11
4   87  103 1 15 23 72 3
8   2
10
65 34 18 29

I would like to write a function that reshapes it into a matrix by the size prompted by the user and it the matrix size given is bigger that the number of elements, it would return with a message.我想写一个 function ,它通过用户提示的大小将其重塑为矩阵,并且给定的矩阵大小大于元素的数量,它会返回一条消息。

but I'm unable to enter the integers of the file, or I don't know how但我无法输入文件的整数,或者我不知道如何

for example:例如:

If you attempt to reshape it to a 4 by 6 matrix, you should get a message like:如果您尝试将其重塑为 4 x 6 矩阵,您应该会收到如下消息:

Cannot reshape matrix: not enough matrix elements

and leaves the file as is.并保持文件原样。

The new content of the file, reshaped to a 3 by 6 matrix, would be:文件的新内容,重新整形为 3 x 6 矩阵,将是:

size 4 by 6
 
3712 9011
4 87 10311523723 82
10
65 34 18 29
  
3 7 12 90 11 4 
87 103 1 15 23 72 
3 8 2 10 65 34
#the numbers would be separated by "\t"

so far all I have is this and I'm stuck.到目前为止,我所拥有的就是这个,我被困住了。 I cannot use imports like Numpy.我不能使用像 Numpy 这样的进口产品。

def reshape (nCols, nRows, file):
    matrixSize = int(nCols*nRows)
    count = 0
    matrix = []
    total_numbers = 0
    for line in file :
        parts = line.split()
        total_numbers += len(parts)
    if matrixSize > total_numbers:
        return print("Not enough elements in the matrix")
    else:
        for i in range(0, nRows):
            while len(matrix)> 0: matrix.pop()
            for i in range(count, count+nCols):
                matrix.append(i)
                count+=1
            print(matrix)




getColInteger= int(input("Enter column integer size: "))
getRowsInteger = input("Enter rows integer size: ")
openFile = open("mat.txt", "r+")
toGetReshape = reshape(getColInteger, getRowsInteger, openFile)

you can create one list with all numbers and add each number in matrix.您可以创建一个包含所有数字的列表并将每个数字添加到矩阵中。

check below code:检查以下代码:

def reshape (nCols, nRows, file):
    matrixSize = int(nCols*nRows)
    count = 0
    matrix = []
    numbers = []
    numbers = []
    [numbers.extend(line.strip().split()) for line in file]
    total_numbers = len(numbers)
    if matrixSize > total_numbers:
        return print("Not enough elements in the matrix")
    else:
        for i in range(0, nRows):
            while len(matrix)> 0: matrix.pop()
            for i in range(count, count+nCols):
                matrix.append(numbers[i])
                count+=1
            print(matrix)

getColInteger= int(input("Enter column integer size: "))
getRowsInteger = int(input("Enter rows integer size: "))
openFile = open("test.txt", "r+")
toGetReshape = reshape(getColInteger, getRowsInteger, openFile)

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

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