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

yipeiwu_com5年前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聚类算法之基本K均值实例详解

Python聚类算法之基本K均值实例详解

本文实例讲述了Python聚类算法之基本K均值运算技巧。分享给大家供大家参考,具体如下: 基本K均值 :选择 K 个初始质心,其中 K 是用户指定的参数,即所期望的簇的个数。每次循环中,...

Python简单实现区域生长方式

区域生长是一种串行区域分割的图像分割方法。区域生长是指从某个像素出发,按照一定的准则,逐步加入邻近像素,当满足一定的条件时,区域生长终止。区域生长的好坏决定于1.初始点(种子点)的选取。...

对Python中创建进程的两种方式以及进程池详解

在Python中创建进程有两种方式,第一种是: from multiprocessing import Process import time def test(): whil...

Python正则表达式匹配日期与时间的方法

下面给大家介绍下Python正则表达式匹配日期与时间 #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Ran...

Python中的ctime()方法使用教程

 ctime()方法转换,因为历元到表示本地时间的字符串表示以秒为单位的时间。如果不设置秒时或None,所返回的时间的当前time()被使用。使用asctime(localti...