By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,354 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

change textfile to a matrix format

P: 9
Dears,
I have a text file that is regular like a matrix, I want to have a program to read it in matrix format to knows rows and columns. ofcourse this file is mixture of digits and words somthings like this.
[1 qw 23 rg 4 4
1 w 4 32 s 9]
Help me ,
Best wishes,
Ayat.
Apr 21 '09 #1
Share this Question
Share on Google+
2 Replies


micmast
100+
P: 144
I assume the values are seperated by a space and a newline equals a new matrix line.

Also I will only write this in psuedo code since I don't feel like coding atm, yet I do want to answer :)

Expand|Select|Wrap|Line Numbers
  1. f = open("file.txt","r")
  2. matrix = ()
  3. counter = 0
  4. line = f.readline()
  5. while line <> "":
  6.    matrix[counter] = line.split(" ")
  7.    line = f.readline()
  8.    counter = counter + 1
  9.  
What does it do:
First read a file, create a few variables and loop through the file and split the line and add it to the matrix in a new row
Apr 21 '09 #2

bvdet
Expert Mod 2.5K+
P: 2,851
Since you have not shown an effort to code it yourself, I won't provide a complete solution. This uses a list comprehension:
Expand|Select|Wrap|Line Numbers
  1. >>> s = "[1 qw 23 rg 4 4\n1 w 4 32 s 9]"
  2. >>> [item.split() for item in s.split('\n')]
  3. [['[1', 'qw', '23', 'rg', '4', '4'], ['1', 'w', '4', '32', 's', '9]']]
  4. >>> 
Apr 21 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.