09 June 2007

Translate your text using Google Api's

Here is how you can translate a Text using Google's "Unofficial" API's.

The URL for Google Translate is - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}

  • "text" is your input string which needs to be translated.
  • langpair is the language pairs involved in the tranlsation. E.g. "ar|en" means translate from Arabic to English.

The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text.

Below is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.

/// <summary>

/// Translate Text using Google Translate API's

/// Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}

/// </summary>

/// <param name="input">Input string</param>

/// <param name="languagePair">2 letter Language Pair, delimited by "|".

/// E.g. "ar|en" language pair means to translate from Arabic to English</param>

/// <returns>Translated to String</returns>

public string TranslateText(

    string input,

    string languagePair)

{

    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

    WebClient webClient = new WebClient();

    webClient.Encoding = System.Text.Encoding.UTF8;

    string result = webClient.DownloadString(url);

    result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);

    result = result.Substring(0, result.IndexOf("</div"));

    return result;

}

More details about this Unofficial Google Translation API can be found Here

Filed under: , ,
 

Comments

# Be Geek My Friend said:

Hoy en cosas interesantes: API´s de Google para traducir texto, Clusters en Windows Server 2008, El MSDTC

10 June 07 at 5:47 AM
# ScottIsAFool said:

Very nice :) Have just created a plugin for Live Writer that uses this :)

SL

14 June 07 at 7:04 AM
# ScottIsAFool said:

Here's the plugin if you're interested :) http://gallery.live.com/liveItemDetail.aspx?li=38d0274a-1d4f-47a3-bf44-9b37b922c48b

14 June 07 at 2:55 PM
# shahpiyush said:

Excellent. I will try it out. Thanks.

14 June 07 at 4:30 PM
# z3nny said:

Exist some code to translate using vba excel ¿?

please help me

z3nny130@gmail.com

14 June 07 at 7:02 PM
# shahpiyush said:

Sorry I dont know much about VBA Excel. But, here is the same code in VB.Net -

   ''' <summary>

   ''' Translate Text using Google Translate API's

   ''' Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}

   ''' </summary>

   ''' <param name="input">Input string</param>

   ''' <param name="languagePair">2 letter Language Pair, delimited by "|".

   ''' E.g. "ar|en" language pair means to translate from Arabic to English</param>

   ''' <returns>Translated to String</returns>

   Public Function TranslateText(ByVal input As String, ByVal languagePair As String) As String

       Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair)

       Dim webClient As New System.Net.WebClient()

       webClient.Encoding = System.Text.Encoding.UTF8

       Dim result As String = webClient.DownloadString(url)

       result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500)

       result = result.Substring(0, result.IndexOf("</div"))

       Return result

   End Function

You could create a COM Callable Wrapper around the class which has this method and use that with VBA.

14 June 07 at 7:17 PM
# Ryan Nohr said:

Awesome Tutorial, very useful, thanks!

27 June 07 at 5:15 PM
# Dorado said:

Does anyone know how to use Google API to translate from classic ASP?  

Google Translation is working beautifully on my site for languages beyond English but it translates the values in my dropdown values which are used for searching the database, therefore all searches fail since the database values are in English.

I was hoping to find a javascript method of Google API (NOT PHP) that would convert a value I pass it back to English.

01 August 07 at 8:51 PM
# shahpiyush said:

For Javascript, you can use XmlHttpRequest in place of WebClient() to call Google's API and perform the translation logic. Check back in a few days I will post sample code to be used from Javascript.

01 August 07 at 8:56 PM
# Dorado said:

Fantastic!  I really appreciate it.

01 August 07 at 9:41 PM
# Franklin said:

Me to. Was looking for something in javascript. I hope you would have done with it by now Shahpiyuish.

THanks.

31 August 07 at 6:59 AM
# Biffity said:

Google do block access after a few attempts so you'll have to put some clever tricks in to stop this happening.

05 September 07 at 9:36 AM
# Peque said:

I trying add this function on my application but first show me a error by Authentification, then add these code lines

'Set the system proxy with valid server address or IP and port.

           Dim pry = New System.Net.WebProxy(uri)

           'The DefaultCredentials automically get username and password.

           pry.Credentials = CredentialCache.DefaultCredentials

           GlobalProxySelection.Select = pry

Now I get the error 403:Forbidden.

Somebody can help me please?

Public Function TranslateText(ByVal input As String, ByVal languagePair As String) As String

       Try

           Dim url As String = [String].Format("http://www.google.com/translate_t?hl&text={0}&langpair={1}", input, languagePair)

           Dim uri As Uri = New Uri(url)

           Dim webCliente As New System.Net.WebClient

           'Set the system proxy with valid server address or IP and port.

           Dim pry = New System.Net.WebProxy(uri)

           'The DefaultCredentials automically get username and password.

           pry.Credentials = CredentialCache.DefaultCredentials

           GlobalProxySelection.Select = pry

           Dim DatosRegresados As System.IO.Stream = webCliente.OpenRead(url)

           Dim result As String = DatosRegresados.ToString

           result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500)

           result = result.Substring(0, result.IndexOf("</div"))

           Return result

       Catch ex As Exception

           MsgBox(ex.Message, MsgBoxStyle.Exclamation)

       End Try

   End Function

28 September 07 at 11:47 AM
# Hiren said:

Thanks Piyush. I will try this out.

12 October 07 at 11:08 PM
# ayoub said:

dont understand how and where will i put the my website name which will be translated .

15 October 07 at 6:38 PM
# Chirag said:

hi it's good but its give me error like length parameter must be greater

18 October 07 at 9:28 AM
# shahpiyush said:

Chirag,

Please post your code.

Thanks.

18 October 07 at 1:12 PM
# shahpiyush said:

ayoub,

I don't get your question. This function is used to translate a string and not a webpage. Please give more specifics of what you are trying to accomplish?

18 October 07 at 1:14 PM
# Chirag said:

hi piyush,

Below is my code

Public Function TranslateText(ByVal input As String, ByVal languagePair As String) As String

       Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair)

       Dim webClient As New System.Net.WebClient

       'webClient. = System.Text.Encoding.UTF8

       Dim result As String

       'result = webClient.Downloadstring(url)

       Dim DatosRegresados As System.IO.Stream = webClient.OpenRead(url)

       result = DatosRegresados.ToString

       result = result.Substring(result.IndexOf("id=txt") + 22, result.IndexOf("id=txt") + 500)

       result = result.Substring(0, result.IndexOf("</div"))

       Return result

   End Function

i am passing this value TranslateText(Me.txt.Text, "en|ar")

and code gives me below error

Index and length must refer to a location within the string. Parameter name: length

19 October 07 at 3:01 AM
# Kishore said:

I am using asp.net 1.1 , the article which u gave is not working

i coded like this

Public Function TranslateText(ByVal input As String="Kishore", ByVal languagePair As String="en|ru") As String

       Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair)

       Dim webClient As New System.Net.WebClient

       'webClient.Encoding = System.Text.Encoding.UTF8

       Dim result As Byte() = webClient.DownloadData(url)

       Dim result1 As String = System.Text.Encoding.GetEncoding("utf-8").GetString(result)

       'result1 = result1.Substring(result1.IndexOf("id=result_box") + 22, result1.IndexOf("id=result_box") + 500)

       'result1 = result1.Substring(0, result1.IndexOf("</div"))

       Return result1

   End Function

please give me ur suggestions

19 October 07 at 6:07 AM
# z3nny said:

Can anyone help me to use this function with excel vba???

please try but without results...

20 November 07 at 7:29 PM
# stedawa said:

Try here

http://www.dailydoseofexcel.com/archives/2004/04/30/translating-text/

22 November 07 at 3:34 AM
# xalnaga said:

I am trying to translate to or from russian but it doesn't translate correctly. I am using vb.net. Does anyone has an idea?

27 November 07 at 7:26 AM
# Hiren said:

Hi Piyush,

Just to let you know that I had implemented it and it helped, thanks allot!

30 November 07 at 1:05 AM
# Google translation application « Burela’s house-o-blog said:

PingBack from http://davidburela.wordpress.com/2007/12/02/google-translation-application/

01 December 07 at 10:27 PM
# jacob said:

is there any script that I can add to my future page to be displayed in different languges.

tank you

15 April 08 at 3:48 AM
# Abadit said:

I am developing a website. the company wants to translate the database contents from english to german as well as other text of the website. I am using asp classic for development.

Can anyone guide me?

16 May 08 at 9:56 AM
# Rob said:

Check out the new improved code at

http://get-dugg.com/google-translate-api-code

10 July 08 at 7:31 AM
# VB .NET - Strings mit Google uebersetzen - daheads blog?? said:

PingBack from http://habari.dahead.de/vb-net---strings-mit-google-uebersetzen

10 July 08 at 5:47 PM
# Vibhav said:

hi piyush,

Below is the code

Public Function TranslateText(ByVal input As String, ByVal languagePair As String) As String

      Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair)

      Dim webClient As New System.Net.WebClient

      'webClient. = System.Text.Encoding.UTF8

      Dim result As String

      'result = webClient.Downloadstring(url)

      Dim DatosRegresados As System.IO.Stream = webClient.OpenRead(url)

      result = DatosRegresados.ToString

      result = result.Substring(result.IndexOf("id=txt") + 22, result.IndexOf("id=txt") + 500)

      result = result.Substring(0, result.IndexOf("</div"))

      Return result

  End Function

i am passing this value TranslateText(Me.txt.Text, "en|ar")

and code gives me below error

Index and length must refer to a location within the string. Parameter name: length

09 September 08 at 1:54 AM
# shahpiyush said:

Vibhav,

My guess is the Result you are getting back is empty or does not have the correct length for indexof

09 September 08 at 4:27 AM
# Vibhav said:

Thanks Piyush,

I got the correction....Now it's working fine.

I have one more query for you.

In TranslateText(Me.txt.Text, "en|ar") > "en|ar" will be sort of hard coded thing.

Can we change it Dynamically? On language selection..

09 September 08 at 7:57 AM
# Online Translation Service said:

I have developed http://translator.vndv.com/ page which uses Google AJAX Language API. I also used Google AJAX Language API to translate the user interface of Online Translation Service to the following languages: English, Arabic, Bulgarian, Chinese, Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hindi, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Romanian, Russian, Spanish, Swedish.

19 December 08 at 9:19 AM
# John said:

Here is som code for automation of internet explorer for google translate service. The progam is done in vba.

http://vbaexcel.eu/vba-macro-code/google-translate-by-internet-explorer-automation

02 March 09 at 4:06 PM
# Noir said:

You can also translate your texts using <a href="http://www.french-translator.org" title="French Translator">French Translator</a> .

In any language!

08 March 09 at 6:11 AM
# Mayur Parmar said:

Hi Piyush,

Here is my code as per your suggestion.

I am getting the following error

"Unable to connect to the remote server"

However, when I posted the url with relevant values, it did give me a response i.e. page was loaded in browser.

Please help

-------------------------------------------

url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

           Uri u = new Uri(url);

           System.Net.WebProxy pxy = new System.Net.WebProxy(u);

           pxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

           //System.Net.GlobalProxySelection.Select = pxy;

           System.Net.WebRequest.DefaultWebProxy=pxy;

           System.Net.WebClient webClient = new System.Net.WebClient();

           webClient.Encoding = System.Text.Encoding.UTF8;

           System.IO.Stream iostr = webClient.OpenRead(url);

          result = iostr.ToString();

           result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);

           result = result.Substring(0, result.IndexOf("</div"));

--------------------------------------------

I am using .NET framework 2.0.

06 April 09 at 3:15 AM
# shahpiyush said:

Mayur,

Make sure your web.config has the information of your proxy server -

<system.net>

   <defaultProxy>

     <proxy

          usesystemdefault="False"

          proxyaddress="http://proxyserver:port"

          bypassonlocal="True"

    />

   </defaultProxy>

 </system.net>

06 April 09 at 12:49 PM
# Karthik said:

Hi piyush,

I am trying to get a list of strings from a excel sheet and use google translate to translate them to other languages and then populate the results back to the excal sheet. Can you please tell me how to do this?

Thanks,

karthik

09 April 09 at 3:26 PM
# sampath said:

Hi,

Did any one know what is the langpair for english to Indic translate.

17 April 09 at 3:42 AM
# return said:

Hi :)

I have tried your function to translate English into Vietnamese. But it doesn't display well.

Example:

Input text is 'type words you want to translate here...'

The result is 'Ki&#7875;u ch&#7919; m b&#7841;n mu&#7889;n d&#7883;ch t&#7841;i &#273;y ...'

(The right result must be: 'Kiểu chữ mà bạn muốn dịch tại đây...')

I know the charset of the webResponse is 'ISO-8859-1', how can I set it to UTF8 ?

Can you give me an advise?

Thank you so much. Wish you have fun!

02 May 09 at 12:32 AM
# amit d said:

hi piyush;

Thanks for ur post

i have tried it but error is coming at secondlast line like

Length cannot be less than zero.

Parameter name: length pLzzzz help

my code->

string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

   // string url = String.Format("http://translate.google.com/translate_t?hl=en&ie=UTF8#en|hi|amit");

   WebClient webClient = new WebClient();

   webClient.Encoding = System.Text.Encoding.UTF8;

    string result = webClient.DownloadString(url);

  // System.IO.Stream DatosRegresados = webClient.OpenRead(url);

  // string result = DatosRegresados.ToString();

   result = result.Substring(result.IndexOf("id=result_box1") + 22, result.IndexOf("id=result_box1") + 500);

   result = result.Substring(0, result.IndexOf("</div"));

   return result;

I m passing values->

string res=TranslateText( result_box1 .Text,"en|hi");

13 May 09 at 5:05 AM
# amit d said:

Plzzz Can anybdy hlp me it,s urgent

13 May 09 at 5:12 AM
# Karan said:

How do I implement the same thing in .Net 1.0

I suppose the methods DownloadString and Encoding are not available in .Net 1.0

Help required for the same.

18 May 09 at 5:42 AM
# yogesh said:

where i can find webclient namespace in asp.net

28 May 09 at 8:11 AM
# Piyush Shah s Blog Translate your text using Google Api s | Paid Surveys said:

PingBack from http://paidsurveyshub.info/story.php?title=piyush-shah-s-blog-translate-your-text-using-google-api-s

29 May 09 at 9:10 PM
# Al said:

This is what worked for me!

result = result.Substring(result.IndexOf("id=result_box") + 24, 800);

12 June 09 at 6:44 PM
# davetiye,davetiye sözleri said:

düğün davetiyesi ve davetiye sözleri

18 November 09 at 5:14 AM
# davetiyeci said:

düğün davetiyesi ve davetiye sözleri

19 November 09 at 12:36 AM
New Comments to this post are disabled
Page view tracker