首页 > 解决方案 > 如何从 .t​​xt 文件中的表创建矩阵

问题描述

我需要从文本文件创建一个矩阵。“分隔符”不是恒定的,有时是 5 个空格,有时或多或少。剂量有人知道怎么做吗?

通过使用以下代码,我只是将行分开:

from tkinter import filedialog

# getting file loction and name from user:
file_path = 'file_path'
file = open(file_path) # open the file
lines = file.readlines()

在此处输入图像描述

我希望输出 5 行 3 列的矩阵。

标签: python

解决方案


尝试以下:

import pandas as pd

file_path = 'file_path'

lines = pd.read_csv(file_path, sep=r'\s+')

推荐阅读