2

I am trying to read a .txt file. However, the output is in strings and I don't get the actual array. I present the current and expected outputs below.

import numpy as np
with open('Test.txt') as f:
    A = f.readlines()
    print(A)

The current output is

['[array([[1.7],\n', '       [2.8],\n', '       [3.9],\n', '       [5.2]])]']

The expected output is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
user19862793
  • 169
  • 6
  • 1
    It looks like what you have here is the string representation of a numpy array. As far as I know, there is no ready-made function in numpy to parse this back into an array. If possible, your best bet is probably to fix this issue "upstream" by choosing a better format for writing the array into the file. – Ture Pålsson Sep 10 '22 at 07:16

1 Answers1

1

By using regex and ast.literal_eval :

import re
import ast

#Your output
s = ['[array([[1.7],\n', '       [2.8],\n', '       [3.9],\n', '       [5.2]])]']

#Join them
s = ' '.join(s)

#Find the list in string by regex
s  = re.findall("\((\[[\w\W]*\])\)",s)

#Convert string to list
ast.literal_eval(s[0])

Output:

[[1.7], [2.8], [3.9], [5.2]]

By using regex and eval :

import re

#Your output
s = ['[array([[1.7],\n', '       [2.8],\n', '       [3.9],\n', '       [5.2]])]']

#Join them
s = ' '.join(s)

#Find the list in string by regex
s  = re.findall("\((\[[\w\W]*\])\)",s)

#Convert string to list
eval(s[0])

Output:

[[1.7], [2.8], [3.9], [5.2]]
Shahab Rahnama
  • 982
  • 1
  • 7
  • 14
  • 2
    use [`ast.literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval), normal eval is susceptible to code injection attacks, since the file is not protected in any way. – XxJames07- Sep 10 '22 at 07:20