# babelizer.py - API for simple access to babelfish.altavista.com. # Requires python 2.0 or better. # # See it in use at http://babel.MrFeinberg.com/ """API for simple access to babelfish.altavista.com. Summary: import babelizer print ' '.join(babelizer.available_languages) print babelizer.translate( 'How much is that doggie in the window?', 'English', 'French' ) def babel_callback(phrase): print phrase sys.stdout.flush() babelizer.babelize( 'I love a reigning knight.', 'English', 'German', callback = babel_callback ) available_languages A list of languages available for use with babelfish. translate( phrase, from_lang, to_lang ) Uses babelfish to translate phrase from from_lang to to_lang. babelize(phrase, from_lang, through_lang, limit = 12, callback = None) Uses babelfish to translate back and forth between from_lang and through_lang until either no more changes occur in translation or limit iterations have been reached, whichever comes first. Takes an optional callback function which should receive a single parameter, being the next translation. Without the callback returns a list of successive translations. It's only guaranteed to work if 'english' is one of the two languages given to either of the translation methods. Both translation methods throw exceptions which are all subclasses of BabelizerError. They include LanguageNotAvailableError Thrown on an attempt to use an unknown language. BabelfishChangedError Thrown when babelfish.altavista.com changes some detail of their layout, and babelizer can no longer parse the results or submit the correct form (a not infrequent occurance). BabelizerIOError Thrown for various networking and IO errors. Version: $Id$ Author: Jonathan Feinberg """ import re, string, urllib """ Various patterns I have encountered in looking for the babelfish result. We try each of them in turn, based on the relative number of times I've seen each of these patterns. $1.00 to anyone who can provide a heuristic for knowing which one to use. This includes AltaVista employees. """ __where = [ re.compile(r'lang=..>([^<]*)'), re.compile(r'div style=padding:10px;>([^<]+)