Connecting Tech Pros Worldwide Forums | Help | Site Map

change textfile to a matrix format

Newbie
 
Join Date: Jan 2009
Posts: 8
#1: Apr 21 '09
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.

micmast's Avatar
Familiar Sight
 
Join Date: Mar 2008
Location: Belgium
Posts: 137
#2: Apr 21 '09

re: change textfile to a matrix format


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
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,564
#3: Apr 21 '09

re: change textfile to a matrix format


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. >>> 
Reply


Similar Python bytes