Coolest Python recipe of all time
Trent Nelson
trent at snakebite.org
Mon May 9 05:31:07 EDT 2011
> What are your favorites?
I think I've posted this before, but I love my 3-lines-if-you-ignore-the-scaffolding language translator. Not because it's clever code -- quite the opposite, the code is dead simple -- but because it encompasses one of the things I love about Python the most: it gets shit done.
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.
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])
More information about the Python-list
mailing list