python将txt文件读入为np.array的方法
作者:tream733 时间:2023-07-23 08:10:29
原文件:
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
来源:https://blog.csdn.net/tream733/article/details/78863760
标签:python,txt,np.array
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python面向对象 反射原理解析
2021-05-14 08:56:32
Python *args和**kwargs用法实例解析
2023-01-16 18:30:55
sqlserver中比较一个字符串中是否含含另一个字符串中的一个字符
2024-01-21 03:04:47
Python日期的加减等操作的示例
2021-10-06 14:28:14
带你了解MySQL中的事件调度器EVENT
2024-01-18 05:55:16
python实现决策树C4.5算法详解(在ID3基础上改进)
2022-05-06 08:01:57
![](https://img.aspxhome.com/file/2023/9/123849_0s.jpg)
python监控进程状态,记录重启时间及进程号的实例
2022-04-22 07:47:20
微信小程序实现签字功能
2024-04-16 09:26:12
![](https://img.aspxhome.com/file/2023/1/136681_0s.gif)
Python之web模板应用
2021-06-27 10:13:47
Python操作MySQL简单实现方法
2024-01-19 04:45:44
nodeJS express路由学习req.body与req.query方法实例详解
2024-06-05 09:52:34
![](https://img.aspxhome.com/file/2023/3/122383_0s.jpg)
axios接口管理优化操作详解
2024-04-30 10:28:09
tensorflow tf.train.batch之数据批量读取方式
2023-12-08 01:11:51
Vue父子组建的简单通信之控制开关Switch的实现
2024-06-05 09:16:25
![](https://img.aspxhome.com/file/2023/8/123058_0s.gif)
人工智能学习Pytorch教程Tensor基本操作示例详解
2021-06-14 17:39:22
![](https://img.aspxhome.com/file/2023/6/117936_0s.png)
Python字典fromkeys()方法使用代码实例
2021-07-09 09:54:38
![](https://img.aspxhome.com/file/2023/2/93672_0s.png)
python 用户交互输入input的4种用法详解
2021-09-10 05:19:34
![](https://img.aspxhome.com/file/2023/6/97746_0s.png)
Python多继承原理与用法示例
2023-10-22 21:01:41
![](https://img.aspxhome.com/file/2023/5/105335_0s.png)
用nodejs搭建websocket服务器
2024-05-08 09:36:56
![](https://img.aspxhome.com/file/2023/1/129461_0s.png)
Jupyter notebook 远程配置及SSL加密教程
2021-06-24 07:15:06
![](https://img.aspxhome.com/file/2023/5/115175_0s.jpg)