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

Comments (48)

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

  2. ScottIsAFool says:

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

    SL

  3. shahpiyush says:

    Excellent. I will try it out. Thanks.

  4. z3nny says:

    Exist some code to translate using vba excel ¿?

    please help me

    z3nny130@gmail.com

  5. shahpiyush says:

    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.

  6. Ryan Nohr says:

    Awesome Tutorial, very useful, thanks!

  7. Dorado says:

    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.

  8. shahpiyush says:

    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.

  9. Dorado says:

    Fantastic!  I really appreciate it.

  10. Franklin says:

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

    THanks.

  11. Biffity says:

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

  12. Peque says:

    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

  13. Hiren says:

    Thanks Piyush. I will try this out.

  14. ayoub says:

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

  15. Chirag says:

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

  16. shahpiyush says:

    Chirag,

    Please post your code.

    Thanks.

  17. shahpiyush says:

    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. Chirag says:

    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. Kishore says:

    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

  20. z3nny says:

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

    please try but without results…

  21. xalnaga says:

    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?

  22. Hiren says:

    Hi Piyush,

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

  23. jacob says:

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

    tank you

  24. Abadit says:

    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?

  25. Vibhav says:

    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

  26. shahpiyush says:

    Vibhav,

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

  27. Vibhav says:

    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..

  28. 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.

  29. John says:

    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

  30. Noir says:

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

    In any language!

  31. Mayur Parmar says:

    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.

  32. shahpiyush says:

    Mayur,

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

    <system.net>

       <defaultProxy>

         <proxy

              usesystemdefault="False"

              proxyaddress="http://proxyserver:port&quot;

              bypassonlocal="True"

        />

       </defaultProxy>

     </system.net>

  33. Karthik says:

    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

  34. sampath says:

    Hi,

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

  35. return says:

    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!

  36. amit d says:

    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");

  37. amit d says:

    Plzzz Can anybdy hlp me it,s urgent

  38. Karan says:

    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.

  39. yogesh says:

    where i can find webclient namespace in asp.net

  40. Al says:

    This is what worked for me!

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

  41. düğün davetiyesi ve davetiye sözleri

  42. davetiyeci says:

    düğün davetiyesi ve davetiye sözleri