[Tutor] word replace

j booth j8ooth at gmail.com
Mon Aug 31 00:12:03 CEST 2009


Hello,

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
(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...

this looks sloppy, but for brevity I'll ignore the rest of the code that is
working and post the area I'm having trouble with;

def exchange():
>
>     original = old() # 'old()' parses the txt file and iterates through
> each of the words
>     new = syn() # the processed alternative that I want to replace the
> original with
>
>     try:
>
>         for line in fileinput.input("test.txt",inplace=1):
>             line = line.replace(original, new, 1)
>             print line,
>
>
>     finally:
>         fileinput.close()
>

So, I'm aware that the in the definition 'exchange()' I don't actually parse
the file test again.. the result is that it seems to loop the entire file
everytime it replaces a word; consequently, if there is a word at in the
last paragraph of the file it is also replaced anywhere proceeding that
point. For example:

this is a test for testing sake


will give the result:

this is a trial for testing sake


but...

this is a test for testing sake
> test


will give the result:

this is a trial for trialing sake
> trial
>


Any help will be greatly appreciated! I've been quite slow in figuring out
this problem.. which is funny as I've been able to solve several other
problems that seem as if they should be much more complicated..

thanks for the time..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090830/8cd97f5f/attachment.htm>


More information about the Tutor mailing list