如何将 txt 文件加载到二维矩阵中?

How to load a txt file into 2d matrix?

我相当需要 Python 并且需要一些帮助。我正在尝试加载一个 txt 文件并将其存储为变量 N,其中 N 应该是一个方阵。但是,当我尝试检查时,N 的 ndim() 为 1,列数不等于行数。

我尝试了以下代码:

N = open('Graph2021.txt', 'r').readlines()
N = np.array(M)

有人可以帮忙吗。我附上了 txt 文件的一部分的屏幕截图,以显示用于分隔列的代码的损坏(我认为)。

txt 文件中填满了 0 和 1:

import numpy as np

N_lines = open('Graph2021.txt', 'r').readlines()
N_matrixlist = [list(map(float,i.strip().split(','))) for i in N_lines]
N = np.array(N_matrixlist)

您正在以列表的形式读取文件,每个元素都是一行。但是,根据您的描述,每一行都有 N 元素。当然,它必须由某些东西分隔(白色 space、逗号等)。您必须用该分隔符分隔每一行。

with open('Graph2021.txt', 'r') as the_file:
    M = []
    for each_line in the_file:
        M.append(each_line.split(",")) # , is separator...
    N = np.array(M)

更多pythonic方式:

with open('Graph2021.txt', 'r') as the_file:
    N = np.array([each_line.split(",") for each_line in the_file]) # , is separator...