Python numpy.genfromtxt

372 views Asked by At

Does anyone know, how I could skip the parenthesis from a text file I trying to read using numpy.genfromtxt My data file is of the format

1.466 ((5.68 3.3 45.7)(4.5 6.7 9.5))
1

There are 1 answers

0
unutbu On BEST ANSWER

np.genfromtxt can accept iterators:

import numpy as np
import re

with open('data', 'r') as f:
    lines = (line.replace('(',' ').replace(')',' ') for line in f)
    arr = np.genfromtxt(lines)
print(arr)

yields

[  1.466   5.68    3.3    45.7     4.5     6.7     9.5  ]

Alternatively, you could use (in Python2) the str.translate or (in Python3) the bytes.translate method, which is a bit faster:

import numpy as np
import re

try:
    # Python2
    import string
    table = string.maketrans('()','  ')
except AttributeError:
    # Python3
    table = bytes.maketrans(b'()',b'  ')

with open('data', 'rb') as f:
    lines = (line.translate(table) for line in f)
    arr = np.genfromtxt(lines)
print(arr)