3 Replies - 71399 Views - Last Post: 20 November 2006 - 09:25 AM Rate Topic: -----

#1 Chits01  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-October 06

Reading text file, word by word in python

Posted 10 October 2006 - 07:53 AM

Hello, How may I read a text file word by word. All documentation I have seen so far refers to reading line and full documents scans. I have a text file with ordered records of name, surname and a key. How do I pickup the key for further processing?
Is This A Good Question/Topic? 0
  • +

Replies To: Reading text file, word by word in python

#2 Amadeus  Icon User is offline

  • g+ + -o drink whiskey.cpp
  • member icon

Reputation: 248
  • View blog
  • Posts: 13,506
  • Joined: 12-July 02

Re: Reading text file, word by word in python

Posted 10 October 2006 - 12:24 PM

Once you've read a line into a string, you can use the split or rsplit functions using a space as a delimiter to return a list of the individual words from that line. You could also read the whole file into one string, and do the split.
Was This Post Helpful? 0
  • +
  • -

#11 velcrobandits  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 6
  • Joined: 13-November 06

Re: Reading text file, word by word in python

Posted 15 November 2006 - 12:27 AM

f = open(filename,"r");
lines = f.readlines();
for i in lines:
thisline = i.split(" ");
#this line is an array of words in a given line. you have split the line which #was a string into an array of words cuz you split the string every time you encountered a space.
Was This Post Helpful? 1

#27 samuraisam  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 1
  • Joined: 20-November 06

Re: Reading text file, word by word in python

Posted 20 November 2006 - 09:25 AM

f = open('myfile.txt', 'r')
all_words = map(lambda l: l.split(" "), f.readlines())

Then iterate through all_words.

-Sam
Was This Post Helpful? 1

Page 1 of 1