[Tutor] Fwd: thesaurus

Rich Lovely roadierich at googlemail.com
Thu Jul 9 03:41:28 CEST 2009


2009/7/9 Pete Froslie <froslie at gmail.com>:
>
>
> ---------- Forwarded message ----------
> From: Pete Froslie <froslie at gmail.com>
> Date: Wed, Jul 8, 2009 at 8:53 PM
> Subject: Re: [Tutor] thesaurus
> To: Robert Berman <bermanrl at cfl.rr.com>
>
>
> Thanks Robert,
>
> I will try this out.. at the moment I'm playing with an API from
> 'http://words.bighugelabs.com/'. It works and pulls the synonyms into
> python. It cost money if you want to process more than 10,000 in a day
> though.
>
> I do have another pretty noob question that I'm figuring out -- once I have
> a list of synonyms returned, is there a simple way to replace the words I
> looked up inside of the 'txt' file?
>
> For instance, I open and read the 'txt' file, grab the first word, search it
> with the thesaurus, get the result, write the result back to the file, and
> then grab the next word to repeat the process. It seems like there is
> probably a quick shortcut for this..
>
> thanks so much
>
>
>

Assuming lookup() handles punctuation and capitalisation...

import sys

if sys.version_info < (2,5):
    print "This script needs a more recent version of python"
    sys.exit(1)
elif sys.version_info < (2,6):
    from __future__ import with_statement

buff = []
with open("path_to_input_file", "r") as fin:
    for line in fin:
        buff.append(" ".join(lookup(word) for word in line.split()))

with open("path_to_output_file", "w") as fout:
    fout.write("\n".join(buff))

This is also a good intro to the with statement, which cleans
everything up for you.  Unfortunatly, it was only introduced in 2.5 as
a __future__ feature, and 2.6 as a final feature.  If you've got a
version prior to that, you'll need to rework it a little, or upgrade.

But I think this gives the general idea.  I don't think there's any
more concise way of doing it than that in python.

You also might want to use print instead of writing straight to a
file, and use the terminal's stream redirection to put the output into
a file.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com


More information about the Tutor mailing list