Click here to Skip to main content
11,709,220 members (58,888 online)
Click here to Skip to main content

Google Translator

, 6 Aug 2015 CPOL 496.5K 23.3K 244
Rate this:
Please Sign up or sign in to vote.
An object that harnesses the power of Google's online natural language translation tools.

Note:
GoogleTranslator was originally written when screen scraping was the only way to access Google's online translation tools. As has been rightly pointed out in this article's forum, a more modern approach would be to use Google's AJAX APIs. See this link for more information. This screen scraper version of GoogleTranslator continues to be maintained at the request of CP readers.

This latest version of GoogleTranslator utilizes Google Translate's AJAX APIs to translate text and retrieves the translation by parsing the returned JSON content. Thanks to CPians @Member 9899010 and @bgsjust for pointing me to these APIs. The latest version of the code also includes the ability to speak the translation from the demo app. Because Google limits the speech to common words in a few languages, don't be surprised if the demo plays dumb when you try to speak your translated text!

What is it?

GoogleTranslator in action GoogleTranslator is an object that allows you to translate text using the power of Google's online language tools. The demo app also allows you to easily perform a reverse translation. The app can be used as a poor man's resource translator for simple phrases, but you'd be wise to confirm the translation with a native speaker before using the results.

How do I use it?

You use GoogleTranslator by constructing it and calling its Translate() method.

 
    using RavSoft.GoogleTranslator;
    
    Translator t = new GoogleTranslator();
    string translation = t.Translate ("Hello, how are you?", "English", "French");
    Console.WriteLine (translation);
    Console.WriteLine ("Translated in " + t.TranslationTime.TotalMilliseconds + " mSec");
    Console.WriteLine ("Translated speech = " + t.TranslationSpeechUrl);

How it works

GoogleTranslator works by directly invoking Google's translation API called by its online translation form and parsing the results.

 
    // Initialize
    this.Error = null;
    this.TranslationSpeechUrl = null;
    this.TranslationTime = TimeSpan.Zero;
    DateTime tmStart = DateTime.Now;
    string translation = string.Empty;

    try {
        // Download translation
        string url = string.Format ("https://translate.google.com/translate_a/single?client=t&sl={0}" +
                                    "&tl={1}&hl=en&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t" +
                                    "&dt=at&ie=UTF-8&oe=UTF-8&source=btn&ssel=0&tsel=0&kc=0&q={2}",
                                    Translator.LanguageEnumToIdentifier (sourceLanguage),
                                    Translator.LanguageEnumToIdentifier (targetLanguage),
                                    HttpUtility.UrlEncode (sourceText));
        string outputFile = Path.GetTempFileName();
        using (WebClient wc = new WebClient ()) {
            wc.Headers.Add ("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 " +
                                          "(KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
            wc.DownloadFile(url, outputFile);
        }

        // Get translated text
        if (File.Exists (outputFile)) {

            // Get phrase collection
            string text = File.ReadAllText(outputFile);
            int index = text.IndexOf (string.Format(",,\"{0}\"", Translator.LanguageEnumToIdentifier (sourceLanguage)));
            if (index == -1) {
                // Translation of single word
                int startQuote = text.IndexOf('\"');
                if (startQuote != -1) {
                    int endQuote = text.IndexOf('\"', startQuote + 1);
                    if (endQuote != -1) {
                        translation = text.Substring(startQuote + 1, endQuote - startQuote - 1);
                    }
                }
            }
            else {
                // Translation of phrase
                text = text.Substring(0, index);
                text = text.Replace("],[", ",");
                text = text.Replace("]", string.Empty);
                text = text.Replace("[", string.Empty);
                text = text.Replace("\",\"", "\"");
            }

            // Get translated phrases
            string[] phrases = text.Split (new[] { '\"' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i=0; (i < phrases.Count()); i += 2) {
                string translatedPhrase = phrases[i];
                if (translatedPhrase.StartsWith(",,")) {
                    i--;
                    continue;
                }
                translation += translatedPhrase + "  ";
            }

            // Fix up translation
            translation = translation.Trim();
            translation = translation.Replace(" ?", "?");
            translation = translation.Replace(" !", "!");
            translation = translation.Replace(" ,", ",");
            translation = translation.Replace(" .", ".");
            translation = translation.Replace(" ;", ";");

            // And translation speech URL
            this.TranslationSpeechUrl = string.Format ("https://translate.google.com/translate_tts?ie=UTF-8"+
                                                       "&q={0}&tl={1}&total=1&idx=0&textlen={2}&client=t",
                                                       HttpUtility.UrlEncode (translation),
                                                       Translator.LanguageEnumToIdentifier (targetLanguage),
                                                       translation.Length);
        }
    }
    catch (Exception ex) {
        this.Error = ex;
    }

    // Return result
    this.TranslationTime = DateTime.Now - tmStart;
    return translation;

As you can see, the logic used to parse the JSON result is very simple!

Speaking the translation

The Translator object retrieves the URL that will stream the spoken version of the translation. The demo app speaks this content by navigating to this URL in a hidden browser control. As mentioned in the preamble, because Google limits the speech to common words in a few languages, don't be surprised if the demo plays dumb when you try to speak your translated text!

Revision History

  • 6 Aug 2015
    Corrected parsing logic.  Fix identified by Member 11019371.  Thank you!
  • 6 May 2015
    Corrected parsing logic to fix translation of single words.
  • 5 May 2015
    Corrected Google URL.
    Removed all external dependencies.
  • 9 Mar 2014
    Switched to using Google's JSON translation APIs.
    Added TranslationTime and TranslationSpeakUrl properties.
    Tweaked demo app UI to assist in reverse translation and resetting an English source and target.
  • 13 Jan 2013
    Added support for current full language set.
    Refixed bug that limited translation to first sentence.
    Fixed a bug that caused reverse translation to fail when accented characters were present.
  • 10 Mar 2010
    Added support for current full language set.
    Fixed bug that limited translation to first sentence.
  • 15 Feb 2010
    Even more parsing tweakage.
  • 28 Mar 2009
    More parsing tweakage.
  • 20 Mar 2007
    Tweaked parsing logic to conform to changes at Google's website.
  • 15 Jan 2006
    Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ravi Bhavnani
Technical Lead
Canada Canada
Ravi Bhavnani is an ardent fan of Microsoft technologies who loves building Windows apps, especially PIMs, system utilities, and things that go bump on the Internet. During his career, Ravi has developed expert systems, desktop imaging apps, marketing automation software, EDA tools, a platform to help people find, analyze and understand information, trading software for institutional investors and advanced data visualization solutions. He currently works for a company that provides enterprise workforce management solutions to large clients.

His interests include the .NET framework, reasoning systems, financial analysis and algorithmic trading, NLP, HCI and UI design. Ravi holds a BS in Physics and Math and an MS in Computer Science and was a Microsoft MVP (C++ and C# in 2006 and 2007). He is also the co-inventor of 2 patents on software security and generating data visualization dashboards. His claim to fame is that he crafted CodeProject's "joke" forum post icon.

Ravi's biggest fear is that one day he might actually get a life, although the chances of that happening seem extremely remote.

You may also be interested in...

Comments and Discussions

 
GeneralRe: Proxy Pin
anga7-Feb-13 19:09
memberanga7-Feb-13 19:09 
GeneralRe: Proxy Pin
anga12-May-13 21:39
memberanga12-May-13 21:39 
GeneralRe: Proxy Pin
Ravi Bhavnani13-May-13 2:22
professionalRavi Bhavnani13-May-13 2:22 
AnswerRe: Proxy Pin
bgsjust28-Aug-13 7:44
professionalbgsjust28-Aug-13 7:44 
GeneralRe: Proxy Pin
Ravi Bhavnani28-Aug-13 7:45
professionalRavi Bhavnani28-Aug-13 7:45 
GeneralRe: Proxy Pin
bgsjust28-Aug-13 8:02
professionalbgsjust28-Aug-13 8:02 
Questionenglish into urdu Pin
Member 930213510-Jan-13 8:44
memberMember 930213510-Jan-13 8:44 
AnswerRe: english into urdu Pin
Ravi Bhavnani10-Jan-13 8:53
memberRavi Bhavnani10-Jan-13 8:53 
GeneralRe: english into urdu Pin
Member 930213513-Jan-13 7:18
memberMember 930213513-Jan-13 7:18 
GeneralRe: english into urdu Pin
Ravi Bhavnani13-Jan-13 8:40
memberRavi Bhavnani13-Jan-13 8:40 
AnswerRe: english into urdu Pin
bgsjust29-Aug-13 13:58
professionalbgsjust29-Aug-13 13:58 
GeneralRe: english into urdu Pin
Ravi Bhavnani30-Aug-13 2:46
professionalRavi Bhavnani30-Aug-13 2:46 
QuestionStringParser not found Pin
Bhavika.R27-Dec-12 0:25
memberBhavika.R27-Dec-12 0:25 
AnswerRe: StringParser not found Pin
Ravi Bhavnani27-Dec-12 5:38
memberRavi Bhavnani27-Dec-12 5:38 
Please check your project references.  You can also obtain the full source for StringParser here[^].

Cheers,

/ravi
My new year resolution: 2048 x 1536
Home | Articles | My .NET bits | Freeware
ravib(at)ravib(dot)com

QuestionGreat job!! Pin
deddy8316-Dec-12 20:24
memberdeddy8316-Dec-12 20:24 
AnswerRe: Great job!! Pin
Ravi Bhavnani17-Dec-12 1:41
memberRavi Bhavnani17-Dec-12 1:41 
AnswerRe: Great job!! Pin
Ravi Bhavnani7-Feb-13 7:38
memberRavi Bhavnani7-Feb-13 7:38 
QuestionJapanese~ Pin
kuronekoneko9-Dec-12 16:28
memberkuronekoneko9-Dec-12 16:28 
AnswerRe: Japanese~ Pin
Ravi Bhavnani10-Dec-12 7:56
memberRavi Bhavnani10-Dec-12 7:56 
GeneralRe: Japanese~ Pin
kuronekoneko11-Dec-12 7:31
memberkuronekoneko11-Dec-12 7:31 
GeneralRe: Japanese~ Pin
Ravi Bhavnani11-Dec-12 7:43
memberRavi Bhavnani11-Dec-12 7:43 
QuestionNice Pin
ario rakip29-Nov-12 2:27
memberario rakip29-Nov-12 2:27 
AnswerRe: Nice Pin
Ravi Bhavnani29-Nov-12 2:30
memberRavi Bhavnani29-Nov-12 2:30 
QuestionRequest in VB.Net Pin
irvieboy19-Nov-12 21:17
memberirvieboy19-Nov-12 21:17 
AnswerRe: Request in VB.Net Pin
Ravi Bhavnani20-Nov-12 2:15
memberRavi Bhavnani20-Nov-12 2:15 
QuestionGreat work - Here is a little bug fix ... Pin
John Whiteman21-Aug-12 2:06
memberJohn Whiteman21-Aug-12 2:06 
AnswerRe: Great work - Here is a little bug fix ... Pin
Ravi Bhavnani21-Aug-12 4:18
memberRavi Bhavnani21-Aug-12 4:18 
QuestionAuto-detect Pin
KendoTM31-Jul-12 0:21
memberKendoTM31-Jul-12 0:21 
AnswerRe: Auto-detect Pin
Ravi Bhavnani31-Jul-12 2:17
memberRavi Bhavnani31-Jul-12 2:17 
BugThe bug that limits the translation of the first sentence again? Pin
Member 462172825-Jul-12 2:18
memberMember 462172825-Jul-12 2:18 
GeneralRe: The bug that limits the translation of the first sentence again? Pin
Member 462172825-Jul-12 2:30
memberMember 462172825-Jul-12 2:30 
GeneralRe: The bug that limits the translation of the first sentence again? Pin
Ravi Bhavnani25-Jul-12 3:26
memberRavi Bhavnani25-Jul-12 3:26 
AnswerRe: The bug that limits the translation of the first sentence again? Pin
Ravi Bhavnani13-Jan-13 8:42
memberRavi Bhavnani13-Jan-13 8:42 
QuestionChinese to English - 2012年06月13日 Pin
devvvy13-Jun-12 23:45
memberdevvvy13-Jun-12 23:45 
AnswerRe: Chinese to English - 2012年06月13日 Pin
Ravi Bhavnani14-Jun-12 1:38
memberRavi Bhavnani14-Jun-12 1:38 
QuestionReally great work! Pin
Vali Radu29-May-12 4:56
memberVali Radu29-May-12 4:56 
AnswerRe: Really great work! Pin
Ravi Bhavnani29-May-12 4:58
memberRavi Bhavnani29-May-12 4:58 
QuestionGoogle Translator Pin
Miguel.Thewolf27-May-12 1:26
memberMiguel.Thewolf27-May-12 1:26 
AnswerRe: Google Translator Pin
Ravi Bhavnani27-May-12 7:27
memberRavi Bhavnani27-May-12 7:27 
QuestionPortuguese to english translation problems Pin
bgsjust18-Apr-12 2:24
memberbgsjust18-Apr-12 2:24 
AnswerRe: Portuguese to english translation problems Pin
Ravi Bhavnani18-Apr-12 6:05
memberRavi Bhavnani18-Apr-12 6:05 
GeneralRe: Portuguese to english translation problems Pin
bgsjust18-Apr-12 9:08
memberbgsjust18-Apr-12 9:08 
GeneralRe: Portuguese to english translation problems Pin
Ravi Bhavnani18-Apr-12 9:23
memberRavi Bhavnani18-Apr-12 9:23 
GeneralRe: Portuguese to english translation problems Pin
bgsjust19-Apr-12 2:18
memberbgsjust19-Apr-12 2:18 
GeneralRe: Portuguese to english translation problems Pin
bgsjust22-Apr-12 11:52
memberbgsjust22-Apr-12 11:52 
AnswerRe: Portuguese to english translation problems Pin
Ravi Bhavnani22-Apr-12 11:54
memberRavi Bhavnani22-Apr-12 11:54 
GeneralRe: Portuguese to english translation problems Pin
bgsjust22-Apr-12 12:01
memberbgsjust22-Apr-12 12:01 
AnswerRe: Portuguese to english translation problems Pin
Ravi Bhavnani13-Jan-13 8:42
memberRavi Bhavnani13-Jan-13 8:42 
GeneralRe: Portuguese to english translation problems Pin
bgsjust13-Jan-13 9:40
memberbgsjust13-Jan-13 9:40 
GeneralMy vote of 5 Pin
reza-mohamad13-Apr-12 8:06
memberreza-mohamad13-Apr-12 8:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 6 Aug 2015
Article Copyright 2006 by Ravi Bhavnani
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid