Google Translate

From PostgreSQL wiki
Jump to: navigation, search

Library Snippets

Translate strings using Google Translate

Works with PostgreSQL

Any version

Written in


Depends on


This function translates a string using the Google Translate service.

CREATE OR REPLACE FUNCTION gtranslate(src text, target text, phrase text) RETURNS text
LANGUAGE plpythonu
AS $$
import re
import urllib

import simplejson as json

class UrlOpener(urllib.FancyURLopener):
        version = "py-gtranslate/1.0"

base_uri = ""
default_params = {'v': '1.0'}

def translate(src, to, phrase):
        args = default_params.copy()
                'langpair': '%s%%7C%s' % (src, to),
                'q': urllib.quote_plus(phrase),
        argstring = '%s' % ('&'.join(['%s=%s' % (k,v) for (k,v) in args.iteritems()]))
        resp = json.load(UrlOpener().open('%s?%s' % (base_uri, argstring)))
                return resp['responseData']['translatedText']
                # should probably warn about failed translation
                return phrase

return translate(src, target, phrase)

The code was originally derived from the code provided at .


SELECT gtranslate('de', 'en', 'Die Würde des Menschen ist unantastbar. Sie zu achten und zu schützen ist Verpflichtung aller staatlichen Gewalt.');
 Human dignity is inviolable. To respect and protect it shall be the duty of all state authority.
(1 row)

(from the constitution of the Federal Republic of Germany)