python读入txt数据,并转成矩阵
txt文件的部分数据截图如下图。数据链接:https://pan.baidu.com/s/1_Ce6WLGDTWf7qQIvpP-70Q 提取码:n22a
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))
结果如下:
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16