Reputation: 323
I'm trying to find the number of rows and columns in a matrix file. The matrix doesn't have spaces between the characters but does have separate lines. The sample down below should return 3 rows and 5 columns but that's not happening.
Also when I print the matrix each line has \n in it. I want to remove that. I tried .split('\n')
but that didn't help. I ran this script earlier with a different data set separated with commas I had the line.split(',')
in the code and that worked it would return the correct number of rows and columns as well as print the matrix with no \n
, I'm not sure what changed by removing the comma from the line.split()
.
import sys
import numpy
with open(sys.argv[1], "r") as f:
m = [[char for char in line.split(' ')] for line in f if line.strip('\n') ]
m_size = numpy.shape(m)
print(m)
print("%s, %s" % m_size)
Sample data:
aaaaa
bbbbb
ccccc
Output:
[['aaaaa\n'], ['bbbbb\n'], ['ccccc']]
3, 1,
Upvotes: 0
Views: 24
Reputation: 120549
IIUC:
with open(sys.argv[1]) as f:
m = np.array([[char for char in line.strip()] for line in f])
>>> m
array([['a', 'a', 'a', 'a', 'a'],
['b', 'b', 'b', 'b', 'b'],
['c', 'c', 'c', 'c', 'c']], dtype='<U1')
>>> m.shape
(3, 5)
Upvotes: 1