python将txt文件读入为np.array的方法

yipeiwu_com6年前Python基础

原文件:

7.8094,1.0804,5.7632,0.012269,0.008994,-0.003469,-0.79279,-0.064686,0.11635,0.68827,5.7169,7.9329,0.010264,0.003557,-0.011691,-0.57559,-0.56121,

原文件数据比较多,是一个125行,45类float数字。

代码:

# -*- coding: utf-8 -*-
import numpy as np

def readFile(path):
 # 打开文件(注意路径)
 f = open(path)
 # 逐行进行处理
 first_ele = True
 for data in f.readlines():
  ## 去掉每行的换行符,"\n"
  data = data.strip('\n')
  ## 按照 空格进行分割。
  nums = data.split(',')
  ## 添加到 matrix 中。
  if first_ele:
   ### 加入到 matrix 中 。
   matrix = np.array(nums)
   first_ele = False
  else:
   matrix = np.c_[matrix,nums]
 matrix = matrix.transpose()
 a = []
 for x in range(0,125):
  result = [float(item) for item in matrix[x]]
  a.append(result)
 arr=np.array(a)
 f.close()
 print(arr)
 return arr
# test.
if __name__ == '__main__':
 readFile("~/s01.txt")

输出:

[[ 8.1305 1.0349 5.4217 ..., 0.74017 0.30053 -0.05773 ]
 [ 8.1305 1.0202 5.3843 ..., 0.73937 0.30183 -0.057514]
 [ 8.1604 1.0201 5.3622 ..., 0.73955 0.30052 -0.057219]
 ..., 
 [ 7.9517 1.1466 5.6081 ..., 0.73945 0.30342 -0.056789]
 [ 7.9743 1.1542 5.5038 ..., 0.7403 0.30027 -0.056704]
 [ 7.9812 1.0945 5.6005 ..., 0.73897 0.30275 -0.056262]]
Process finished with exit code 0

以上这篇python将txt文件读入为np.array的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

简单了解python单例模式的几种写法

方法一:使用装饰器 装饰器维护一个字典对象instances,缓存了所有单例类,只要单例不存在则创建,已经存在直接返回该实例对象。 def singleton(cls): inst...

对于Python中RawString的理解介绍

总结 1、'''作用: 可以表示 "多行注释" 、"多行字符串" 、"其内的单双引号不转义" 2、r 代表的意思是: raw 3、r 只对其内的反斜杠起作用(注意单个 \ 的问题) ra...

python+pandas+时间、日期以及时间序列处理方法

先简单的了解下日期和时间数据类型及工具 python标准库包含于日期(date)和时间(time)数据的数据类型,datetime、time以及calendar模块会被经常用到。 dat...

pytorch 数据集图片显示方法

图片显示 pytorch 载入的数据集是元组tuple 形式,里面包括了数据及标签(train_data,label),其中的train_data数据可以转换为torch.Tensor形...

Python 3.6 中使用pdfminer解析pdf文件的实现

Python 3.6 中使用pdfminer解析pdf文件的实现

所使用python环境为最新的3.6版本 一、安装pdfminer模块 安装anaconda后,直接可以通过pip安装 pip install pdfminer3k  ...