Home > Mobile >  Reading multiple arrays in a text file in Python
Reading multiple arrays in a text file in Python

Time:09-11

I am trying to read multiple arrays saved in .txt file. I present the data in Test.txt file as well as the current and expected outputs.

import re
import numpy as np
import ast

with open('Test.txt') as f:
    s = f.readlines()
    #print(s)
    s = ' '.join(s)
    s  = re.findall("\((\[[\w\W]*\])\)",s)
    s=ast.literal_eval(s[0])
    s=np.array(s)
    print([s])

The data in Test.txt is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]

The current output is

line 4
    [5.2]])]
          ^
SyntaxError: unmatched ')'

The expected output is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]

CodePudding user response:

You can use this:

import re
import ast

s = '''
    [array([[1.7],[2.8],[3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]
'''

s = s.replace('\n', '')
s = s.replace(' ', '')
s = s[1:-1]
s = re.findall("\((\[.*?\])\)",s)

result= []

for i in s:
    result.append(ast.literal_eval(i))
    
print(result)

Output:

[[[1.7], [2.8], [3.9], [5.2]], [[2.1], [8.7], [6.9], [4.9]]]
  • Related