python - 如何在python中读取包含numpy.ndarray的txt文件
问题描述
我想知道读取以下test.txt
包含以下值的文件的正确语法是什么:
(ps test.txt 的类型为 numpy.ndarray)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.51 0.47 0.45
0.42 0.42 0.4 0.385 0.375 0.41 0.415 0.375 0.355 0.36 0.41 0.4
0.39 0.38 0.375 0.375 0.375 0.38 0.39 0.395 0.385 0.38 0.375 0.375
0.37 0.365 0.36 0.355 0.35 0.35 0.345 0.345 0.35 0.36 0.355 0.355
0.35 0.35 0.355 0.355 0.35 0.35 0.35 0.345 0.34 0.335 0.325 0.325
0.325 0.33 0.345 0.325 0.32 0.315 0.315 0.315 0.31 0.31 0.31 0.305
0.305 0.3 0.3 0.29 0.29 0.3 0.295 0.29 0.29 0.29 0.29 0.29]
我尝试使用以下代码读取文件:
data_test = np.genfromtxt('test.txt')
但我收到错误按摩说:
ValueError: Some errors were detected !
Line #43 (got 8 columns instead of 12)
任何有关如何读取这种由空格/列分隔的数据的帮助将不胜感激!
解决方案
with open('test.txt') as file:
data = file.read()
data = data.replace('\n', '')
arr = np.fromstring(data[1:-1], sep=' ', dtype=np.float32)
推荐阅读
- amazon-web-services - Amazon Cognito MFA 以用户为单位?
- javascript - 我可以编写python代码来调用我在本地编写但需要在Chrome控制台中运行的JS脚本吗?
- html - 如何收紧行之间的边距?
- reactjs - > 任务:app:compileDebugJavaWithJavac 失败
- deep-learning - 如何在高分辨率图像上进行目标检测?
- android - 改造:如何将值发送到 REST API 并检查它是否存在?
- kubernetes - Kubernetes HPA 的平滑负载再平衡
- python - 你如何在条件下提高这个 for 循环的速度?
- python - AWS 安全性会不会更令人困惑
- mongodb - 如何为复杂数据结构中的MongoDB时间序列数据编写一次fire and forget $inc查询