Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problems counting rows and columns with no spaces in a matrix

Im 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, Im 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['aaaaa\n'], ['bbbbb\n'], ['ccccc']]
3, 1, 

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading