[Tutor] word replace

Alan Gauld alan.gauld at btinternet.com
Mon Aug 31 01:07:01 CEST 2009


"j booth" <j8ooth at gmail.com> wrote

> I have been experiencing such difficulty with something that should be
> easy-- pretty new to programming..
> 
> Need to:
> (1) open a text file
> (2) iterate through it word by word

And here lies the first problem. Programming languages in general 
don't know much about words(*) (or paragraphs for that matter). They 
know about lines and letters(or characters). So you as programmer 
will have to teach OPython what you mean by a word and how to 
manipulate them

(*)The exception is regular expressions which do have a comcept 
of a word. Whethjer that concept matches yours is another matter 
entirely! :-)

> (3) replace each word with an alternative word and close the file.
> 
> **I don't know what the alternative word will be before running the
> script...

We had a somewhat similar thread a few weeks ago it might be 
worth searching the archives.

> this is a test for testing sake
>> test
> 
> will give the result:
> 
> this is a trial for trialing sake
>> trial

Again Python just replaces a sequence of characters, it has no concept 
of a word.

You might be better working with regular expressions where you 
can define the pattern to be replaced as a whole word only.
Caveat: Regex are much harder to work with than simple strings. 
Be prepared for a lot of trial and error to get the patterns just right.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list