Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python load array from ascii-styled .txt file

Tags:

python

arrays

There's a .txt file called "array.txt" which contains the following 5x5 array of two digit numbers:

+-------------------------+

¦ 34 ¦ 21 ¦ 32 ¦ 41 ¦ 25  ¦

+----+----+----+----+-----¦

¦ 14 ¦ 42 ¦ 43 ¦ 14 ¦ 31  ¦

+----+----+----+----+-----¦

¦ 54 ¦ 45 ¦ 52 ¦ 42 ¦ 23  ¦

+----+----+----+----+-----¦

¦ 33 ¦ 15 ¦ 51 ¦ 31 ¦ 35  ¦

+----+----+----+----+-----¦

¦ 21 ¦ 52 ¦ 33 ¦ 13 ¦ 23  ¦

+-------------------------+

I want a script which reads this file automatically, without having to manually code:

array = np.matrix([[34,21,32,41,25],[14,42,43,14,31],[54,45,52,42,23],[33,15,51,31,35],[21,52,33,13,23]])

All I have is the following:

import numpy as np
np.loadtxt('array.txt', skiprows=1)

which returns the error "ValueError: could not convert string to float: b'xa6'". So it seems as if it doesn't like the ascii characters. Is there any function that can read only the numerical values of a text file into an array? Thanks a lot for reading, any help would be infinitely appreciated.

like image 259
Grassy Avatar asked Feb 01 '26 16:02

Grassy


1 Answers

Here is how to do it in one line, or two:

import re

import numpy as np


numbers = re.compile(r'\d+')

np.array([map(int, numbers.findall(line)) 
          for line in open("array.txt", "r") 
          if numbers.search(line) is not None])
like image 66
logc Avatar answered Feb 04 '26 05:02

logc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!