1

I have a text file, which has the following content:

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) 

How can I read from this text file (e.g with the name 'file.txt') the array arr and convert it to an array with two columns? The output should be:

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]])

If I would have this line:

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 

I could use:

import numpy as np
arr=np.loadtxt('file.txt', delimiter=',')
arr.reshape(-1,2)
2
  • 1
    Read the arr line as a string and manipulate it with Python string methods, replacing characters as needed and splitting. Until you get a list of float-like strings, it's a plain Python task. Commented Feb 10, 2021 at 17:18
  • Seems like line.replace(') (', ',') would do the trick. Commented Apr 1, 2021 at 15:37

1 Answer 1

1

Simple Python will get you to where you can use 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!')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.