1 Replies - 599 Views - Last Post: 22 March 2012 - 09:14 PM Rate Topic: -----

#1 Atropos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-March 12

Python code for storing each word.

Posted 22 March 2012 - 07:53 PM

Hi im new to python and was trying to write a code to read each individual word of each line. I wrote the following code:
#!/usr/bin/env python3

F = open('asd.dat');   
lines = F.readlines();
for i in lines:
    thisline = i.split(" ");
word = [];      
for i in thisline:
        word.append(i.split(" ")) ;
print("thisline",thisline);
print("word", word);
F.close()        


However this just prints the words of the last line? is there a way by which i can get it to print all words?
eg if asd.txt has
hello people
This is python

Can i get the word[] to have [[hello], [people], [This], [is], [python]] ?
I would really appreciate your help!

Is This A Good Question/Topic? 0
  • +

Replies To: Python code for storing each word.

#2 michael072  Icon User is offline

  • D.I.C Head

Reputation: 24
  • View blog
  • Posts: 100
  • Joined: 08-February 11

Re: Python code for storing each word.

Posted 22 March 2012 - 09:14 PM

The reason that's happening is because every time your first loop goes it writes over the old variable so when the next for loop goes it only operates on the last line. What you should do is put the second for loop inside the first one. Remember that in python the indentation matters.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1