change textfile to a matrix format

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • amirayat
    New Member
    • Jan 2009
    • 9

    change textfile to a matrix format

    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
    New Member
    • Mar 2008
    • 144

    #2
    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 :)

    [CODE=python]
    f = open("file.txt" ,"r")
    matrix = ()
    counter = 0
    line = f.readline()
    while line <> "":
    matrix[counter] = line.split(" ")
    line = f.readline()
    counter = counter + 1
    [/CODE]

    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

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Since you have not shown an effort to code it yourself, I won't provide a complete solution. This uses a list comprehension:
      Code:
      >>> s = "[1 qw 23 rg 4 4\n1 w 4 32 s 9]"
      >>> [item.split() for item in s.split('\n')]
      [['[1', 'qw', '23', 'rg', '4', '4'], ['1', 'w', '4', '32', 's', '9]']]
      >>>

      Comment

      Working...