I have the following .txt file:
[0.03932153 0.10188484 0.23541254 0.18962094 0.43376015]
[0.0453733 0.13984493 0.62747017 0.15459015 0.03272145]
[0.0299296 0.1038427 0.74556143 0.03760473 0.08306153]
[0.14998161 0.22125856 0.00924835 0.01314869 0.60636278]
[0.09769381 0.12554495 0.0330114 0.26816809 0.47558175]
I want to read the containing floats and store them into a 2D array.
I tried using regex but wasn't quite sure what the right structure was. Basicaly, do I have to use regex first to remove '[' and ']' ?
Any help is appreciated.
CodePudding user response:
You could use a regex to extract the numbers, and then map those to float
:
with open("test.txt", "r") as f:
result = [
list(map(float, re.findall(r"-?\d (\.\d )?", line)))
for line in f.readlines()
]