Help With EOF character: URGENT

Eric @ Zomething eric at zomething.com
Sun Feb 22 19:21:04 EST 2004


dont bother wrote:

> 
> Hi Buddies,
> I am facing this problem and I dont know what to use
> as EOF in python:
> I want to read a file, and put all the individual
> words in a dictionary with their index:
> For example if the file is:
> 
> Hello there I am doing fine
> How are you?
> 
> So I want to make an index like this:
> 
> 1 Hello
> 2 there
> 3 I
> 4 am
> 5 doing
> 6 fine
> 7 How
> 8 are
> 9 you
> 10 ?
> 
> In order to do this: I have written a small code which
> is here:
> -------------------------------------------------------
> # python code for creating dictionary of words from an
> #input file
> ------------------------------------------------------
> 
> import os
> import sys
> try:
>         fread = open('training_data', 'r')
> except IOError:
>         print 'Cant open file for reading'
>         sys.exit(0)
> print 'Okay reading the file'
> s=""
> a=fread.read(1)
> while (a!="\003"):
> #while 1:
>                 s=s+a
> 

<snip>

Dont, I think you want to iterate over your file, rather than look for an EOF marker, unless you have a technical reason not to.

I'll leave it to someone else to provide a better solution, but here is a Q&D newbie approach to a text file break-out of words:

>>> fileOne=open('C:\\testfile.txt')
>>> fileString=fileOne.read()
>>> print fileString
Hello there I am doing fine
How are you?
>>> wordString=fileString.replace('\n',' ')
>>> print wordString
Hello there I am doing fine How are you? 
>>> wordList=wordString.split(' ')
>>> print wordList
['Hello', 'there', 'I', 'am', 'doing', 'fine', 'How', 'are', 'you?', '']

HTH,

Eric




More information about the Python-list mailing list