Python script to automate use of Google Translate? (or other translator)

Trent Nelson tnelson at onresolve.com
Tue Apr 22 13:52:57 EDT 2008


> > I have the need to occasionally translate a single word
> > programatically. Would anyone have a Python script that
> > would let me do this using Google (or another) translation
> > service?

As a matter of fact, yes, I do!  This happens to be my most favourite piece of Python code I've ever written, too...

In [1]: from translate import *

In [2]: translate('French', 'The quick brown fox jumped over the lazy dog.')
Le renard brun rapide a sauté par-dessus le chien paresseux.

In [3]: translate('German', 'The quick brown fox jumped over the lazy dog.')
Der schnelle braune Fuchs sprang über den faulen Hund.

In [4]: translate('Spanish', 'The quick brown fox jumped over the lazy dog.')
El zorro marrón rápido saltó sobre el perro perezoso.

And translate.py:

    import sys
    from urllib import urlopen, urlencode
    from BeautifulSoup import BeautifulSoup

    url = 'http://babelfish.altavista.com/tr'
    languages = {
        'French'    : 'en_fr',
        'German'    : 'en_de',
        'Italian'   : 'en_it',
        'Spanish'   : 'en_es',
        'Russian'   : 'en_ru',
        'Portuguese': 'en_pt',
        'Dutch'     : 'en_nl',
        'Japanese'  : 'en_ja',
    }

    def translate(lang, text):
        kwds = { 'trtext' : text, 'lp' : languages[lang]}
        soup = BeautifulSoup(urlopen(url, urlencode(kwds)))
        print soup.find('div', style='padding:10px;').string

    if __name__ == '__main__':
        translate(sys.argv[1], sys.argv[2])

Enjoy!


Regards,


        Trent.



More information about the Python-list mailing list