Friday, June 4, 2010

Using YQL and Google Translate to Translate Text

Had a little time to play, so I wanted to see what I could do to internationalize (I think that's a word :) ) my site. I noticed in YQL there was a GoogleTranslate Table, so after some trial and error, found out that with:

select * from json where url='http://www.google.com/uds/Gtranslate?context=22&langpair=%7C" + lang + "&v=1.0&q=" + encodeURIComponent(str) + "'

with the variables being, of course, lang for language symbol (i.e. en for english, de for dutch, etc.) and str for Text String to be translated. Plug that into a YQL Json function and you're set, well, almost...

Why not also scrape the items from the Google Site to use for a Combo Box to select a language from? If you go to: http://translate.google.com, you will see a combo box next to TranslateInto. To Get the data from that, simply use this query as your JSON String:

http://query.yahooapis.com/v1/public/yql?q=select%20option%20from%20html(0)%20where%20url%3D%22http%3A%2F%2Ftranslate.google.com%22%20and%0D%0A%20%20%20%20%20%20xpath%3D'%2F%2Fselect%5B%40class%3D%22tllangdropdown%22%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?

Plug that into the YQL Console, and you will find that you can get the value and Content for items to plug into a combo box of your own.

Finally, wire up the dropdown that was created with an event similar to:

$("#DROPDOWNNAME").change(function () {
translateText($(str).html(), this.value);
});

And you're all done.

I realize this was a very brief explaination, but for the full script simply go to:

http://www.joshuablackstone.com/Scripts/GTranslate.js.

0 comments: