Matlab函数fscanf()似乎非常强大. python(或numpy)中是否有相同的东西?
The Matlab function fscanf() seems to be very powerful. Is there any equivalent of the same in python (or numpy)?
具体来说,我想从文件中读取矩阵,但是我不想遍历每一行以读取矩阵. 这种东西(从matlab读取2D 1000x1000矩阵):
Specifically I want to read a matrix from file but I don't want to iterate through each line to read the matrix. Something of this sort (from matlab for reading a 2D 1000x1000 matrix):
matrix = fscanf(fopen('input.txt'),'%d',[1000,1000]);推荐答案
Python没有内置的fscanf函数.最接近的方法是逐行读取文件并使用正则表达式.
Python has no built-in fscanf function. The closest way to do it is to read the file line by line and use regular expressions.
Numpy (类似于Matlab的Python库)具有允许读取文件的功能.并从is内容构造一个数组: numpy.fromfile (或根据其他答案的建议, numpy.loadtxt 在这种情况下可能更合适.)
Numpy (the Matlab-like Python library), however, has a function that allows to read a file and construct an array from is content : numpy.fromfile (or, as suggested in the other answers, numpy.loadtxt may be more suitable in this case).
更多推荐
Python中的Matlab'fscanf'等效项是什么?
发布评论