繁体   English   中英

如何使用 numpy.loadtxt 读取文本文件的一部分并转换为数组

[英]How to read part of a text file using numpy.loadtxt and convert to array

我有一个文本文件,其中包含以下内容:

type=0
alg=1
c=3 5 7 8 10 11 14 15 16 17 
arr=(0, -7.05154314637184143066e-02) (1, -1.80315405130386352539e-01) (2, -3.32004070281982421875e-01) (3, 5.91193616390228271484e-01) (4, -1.21851079165935516357e-01) (5, -2.71257162094116210938e-01) (6, 2.46545433998107910156e-01) (7, 8.54252055287361145020e-02) 

如何从该文本文件(例如名称为“file.txt”)中读取数组arr并将其转换为具有两列的数组? output 应该是:

array([[ 0.        , -0.07051543],
       [ 1.        , -0.18031541],
       [ 2.        , -0.33200407],
       [ 3.        ,  0.59119362],
       [ 4.        , -0.12185108],
       [ 5.        , -0.27125716],
       [ 6.        ,  0.24654543],
       [ 7.        ,  0.08542521]])

如果我有这条线:

0,-7.05154314637184143066e-02,1,-1.80315405130386352539e-01,2,-3.32004070281982421875e-01,3, 5.91193616390228271484e-01,4,-1.21851079165935516357e-01,5,-2.71257162094116210938e-01,6, 2.46545433998107910156e-01,7,8.54252055287361145020e-02 

我可以使用:

import numpy as np
arr=np.loadtxt('file.txt', delimiter=',')
arr.reshape(-1,2)

简单的 Python 将带您到可以使用np.fromstring的地方:

for line in open('file.txt'):
    if line.startswith('arr='):
        line = line[5:].rstrip().rstrip(')').replace(') (', ',')
        arr = np.fromstring(line, sep=',').reshape(-1, 2)
        break  # or return arr
else:
    raise ValueError('SOL!')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM