python读入txt数据,并转成矩阵

txt文件的部分数据截图如下图。数据链接:https://pan.baidu.com/s/1_Ce6WLGDTWf7qQIvpP-70Q   提取码:n22a

python读入txt数据,并转成矩阵

 python读入该数据,并转成array,代码如下:

import os
import numpy as np

# 数据文件转矩阵
# path: 数据文件路径
# delimiter: 行内字段分隔符

def file2array(path, delimiter):
    recordlist = []
    fp = open(path, ‘r‘, encoding=‘utf-8‘)
    content = fp.read()     # content现在是一行字符串,该字符串包含文件所有内容
    fp.close()
    rowlist = content.splitlines()  # 按行转换为一维表,splitlines默认参数是‘\n’
    # 逐行遍历
    # 结果按分隔符分割为行向量
    recordlist = [row.split(delimiter) for row in rowlist if row.strip()]
    return np.array(recordlist)


root = ‘testdata‘
filelist = os.listdir(root)   # 获取路径下所有数据文件的文件名
for file in filelist[:-1]:
    recordArray = file2array(root + ‘/‘ + file, ‘\t‘)   # 文件到矩阵的转换
    print(‘shape of recordmat: ‘, np.shape(recordArray))

结果如下:

python读入txt数据,并转成矩阵

相关推荐