【问题标题】:numpy.loadtxt to load a filenumpy.loadtxt 加载文件
【发布时间】:2021-09-12 12:35:10
【问题描述】:

我有一个如下所示的文件:

(完整版可以在这里访问:https://drive.google.com/file/d/1uKRgp6X6ZfQbUsEr2bQ3_ZOPZYFSjmhj/view?usp=sharing


[[51, 49, array([[ 67.,   0.,   0.,   0.],
       [  1.,  47.,   0.,   0.],
       [117.,   0.,   0.,   0.],
       [ 10., 126., 109.,   0.],
       [  7.,   0.,   0.,   0.],
       [ 90.,  50.,   0.,   0.],
       [ 50.,   0.,   0.,   0.],
       [  4.,  69.,  40.,  49.]])], 
[70, 49, array([[ 63.,   0.,   0.,   0.],
       [127.,  48.,   0.,   0.],
       [118.,   0.,   0.,   0.],
       [ 52., 125.,  68.,   0.],
       [  2.,   0.,   0.,   0.],
       [ 62., 102.,   0.,   0.],
       [ 84.,   0.,   0.,   0.],
       [ 58.,  89.,   5.,  72.]])],
[75, 49, array([[122.,   0.,   0.,   0.],
       [120., 104.,   0.,   0.],
       [ 86.,   0.,   0.,   0.],
       [104.,  24.,  15.,   0.],
       [ 99.,   0.,   0.,   0.],
       [ 77.,  41.,   0.,   0.],
       [124.,   0.,   0.,   0.],
       [126.,  37.,  73.,  59.]])]

其中的标题是迭代 = 51、值 = 49、角度 = 数组(...)、迭代 = 70... 等等。

如何在我的脚本中加载它?谢谢。

【问题讨论】:

标签: python numpy file-upload


【解决方案1】:

默认的numpy 加载方法在这里不起作用,因为文件没有预期的格式。如果您负责生成此文件,请考虑使用例如numpy.savetxtnumpy.save,因此您可以相应地使用numpy.loadtxtnumpy.load

对于您拥有的文件,如果可以信任源,非常快速和肮脏的解决方案是使用eval 加载此文件。但是,请考虑阅读the dangers of eval,因为它可以执行该文件中的任何代码

假设你已经像这样导入了numpy

import numpy as np

这应该可行:

with open('filename.txt') as file:
    contents = file.read().replace('array', 'np.array')
    data = eval(contents)

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2018-07-16
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多