Click here to Skip to main content
15,909,518 members
Articles / Programming Languages / C#

Google Translator

Rate me:
Please Sign up or sign in to vote.
4.94/5 (143 votes)
17 Mar 2016CPOL2 min read 1.7M   40.1K   278   482
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 @Airstriker82, @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.

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

C#
 
    // 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.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&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.googleapis.com/translate_tts?ie=UTF-8&q={0}&tl={1}&total=1&idx=0&textlen={2}&client=gtx",
                                                       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

  • 18 Mar 2016
    Switched to Google Translate plugin APIs.  Fix identified by User-12366202.  Thank you!
  • 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)


Written By
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 3 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.

Comments and Discussions

 
AnswerRe: Google translate Pin
Ravi Bhavnani12-May-15 3:47
professionalRavi Bhavnani12-May-15 3:47 
QuestionThanks a lot ! Pin
Member 116742217-May-15 21:24
Member 116742217-May-15 21:24 
AnswerRe: Thanks a lot ! Pin
Ravi Bhavnani8-May-15 11:24
professionalRavi Bhavnani8-May-15 11:24 
QuestionNice Article Pin
Avadhesh Kumar Maurya7-May-15 2:52
Avadhesh Kumar Maurya7-May-15 2:52 
AnswerRe: Nice Article Pin
Ravi Bhavnani7-May-15 2:54
professionalRavi Bhavnani7-May-15 2:54 
GeneralMy vote of 5 Pin
Sachin Mahandule6-May-15 19:19
professionalSachin Mahandule6-May-15 19:19 
GeneralRe: My vote of 5 Pin
Ravi Bhavnani7-May-15 2:17
professionalRavi Bhavnani7-May-15 2:17 
Questionsingle work problem Pin
MarkDoubson6-May-15 9:56
MarkDoubson6-May-15 9:56 
try to translate one word from English to French (it can be any languages) - e.g. sparrow
You will receive this:
[[[ , ],[,,, ]],[[ ,[ , , ],[[ ,[ ],,0.45783335, ],[ ,[ ],,0.0033880526, ],[ ,[ ],,0.0024787523, ]], ,1]], ,,,[[ ,1,[[ ,1000,true,false],[ ,0,true,false],[ ,0,true,false],[ ,0,true,false],[ ,0,true,false]],[[0,7]], ,0,1]],0.02046049,,[[ ],,[0.02046049]],,,[[ ,[[[ , ], sparrow noun a small finchlike Old World bird related to the weaverbirds, typically with brown and gray plumage. m_en_us1292816.001 With a beat of her tiny brown wings, the sparrow was on her way. any of a number of birds that resemble true sparrows in size or color. m_en_us1292816.002 sparrow I saw one bird, a tiny \u003cb\u003esparrow\u003c/b\u003e darting through the gnarled pine limbs. m_en_us1292816.001 With a beat of her tiny brown wings, the \u003cb\u003esparrow\u003c/b\u003e was on her way. m_en_us1292816.001 It was a light gray and it had a large black beak, more like a hawk's than a \u003cb\u003esparrow\u003c/b\u003e 's. m_en_us1292816.001 An injured \u003cb\u003esparrow\u003c/b\u003e or a bird dressed for a dining table distresses her as much as war among nations and nuclear experiments do. m_en_us1292816.001 Everything from the modest \u003cb\u003esparrow\u003c/b\u003e to the extravagant scarlet macaw came to perch and settle around her. m_en_us1292816.001 The branches serve as a handy perch for the \u003cb\u003esparrows\u003c/b\u003e and mourning doves that frequent my city bird feeder. m_en_us1292816.001 Crows and \u003cb\u003esparrows\u003c/b\u003e have been known to attack innocent passers-by who happen to stroll near their nests. m_en_us1292816.001 Smaller birds such as pigeons, thrushes, jackdaws, robins and \u003cb\u003esparrows\u003c/b\u003e would also have been seen on a regular basis. m_en_us1292816.001 He fed \u003cb\u003esparrows\u003c/b\u003e and grosbeaks on a seed tray mounted on a pole to be visible from his windows. m_en_us1292816.001 While we don't have tall trees, our neighbors do, and the firs and oaks that surround our property drop acorns and provide homes for jays, woodpeckers, robins and \u003cb\u003esparrows\u003c/b\u003e. m_en_us1292816.001 Growing up, I was fascinated by birds and my mother encouraged this by letting me feed \u003cb\u003esparrows\u003c/b\u003e on the fire-escape outside our window. m_en_us1292816.001 All wild birds (except pigeons, English \u003cb\u003esparrows\u003c/b\u003e and starlings) are protected by federal and state laws, so it's illegal to trap, kill or poison them. m_en_us1292816.001 Game birds, mockingbirds, robins, and \u003cb\u003esparrows\u003c/b\u003e enjoy the juicy, sticky red fruits. m_en_us1292816.001 Some landscapes these days have been reduced to nothing but dandelions and fire ants, knapweed and thistle, where the only remaining wildlife are \u003cb\u003esparrows\u003c/b\u003e, squirrels, and starlings. m_en_us1292816.001 One sparrow box can house up to 36 baby \u003cb\u003esparrows\u003c/b\u003e in a year. m_en_us1292816.001 Stop \u003cb\u003esparrows\u003c/b\u003e and finches from shredding crocus blossoms by placing foil pinwheels - the kind sold for children's Easter baskets - every few feet among the flowers. m_en_us1292816.001 Most folks start with a feeder or two and quickly find themselves engrossed with the resident \u003cb\u003esparrows\u003c/b\u003e, finches, and woodpeckers that eagerly accept the offerings. m_en_us1292816.001 A couple of \u003cb\u003esparrows\u003c/b\u003e who had been peacefully resting on the grey rocks abruptly flew off. m_en_us1292816.001 Budgies, finches, \u003cb\u003esparrows\u003c/b\u003e and canaries are only a few of the more than one hundred kinds of birds people keep in their apartments. m_en_us1292816.001 There is nothing to see except blackbirds and \u003cb\u003esparrows\u003c/b\u003e; nothing to hear except the noise of butterflies' wings. m_en_us1292816.001 sparrow-hawk sparrow hawk

while if your input two same words - sparrow sparrow - you will receive proper answer:
moineau moineau
Mark Doubson

AnswerRe: single work problem Pin
Ravi Bhavnani6-May-15 10:03
professionalRavi Bhavnani6-May-15 10:03 
GeneralRe: single word problem Pin
MarkDoubson6-May-15 10:44
MarkDoubson6-May-15 10:44 
GeneralRe: single word problem Pin
Ravi Bhavnani6-May-15 10:45
professionalRavi Bhavnani6-May-15 10:45 
GeneralRe: single word problem Pin
MarkDoubson6-May-15 10:54
MarkDoubson6-May-15 10:54 
GeneralRe: single word problem Pin
Ravi Bhavnani6-May-15 10:56
professionalRavi Bhavnani6-May-15 10:56 
AnswerRe: single work problem Pin
Ravi Bhavnani6-May-15 10:44
professionalRavi Bhavnani6-May-15 10:44 
AnswerRe: single work problem Pin
Ravi Bhavnani6-May-15 10:56
professionalRavi Bhavnani6-May-15 10:56 
GeneralRe: single work problem Pin
MarkDoubson6-May-15 16:06
MarkDoubson6-May-15 16:06 
QuestionRe: single work problem Pin
Ravi Bhavnani6-May-15 17:15
professionalRavi Bhavnani6-May-15 17:15 
AnswerRe: single work problem Pin
MarkDoubson7-May-15 8:49
MarkDoubson7-May-15 8:49 
GeneralRe: single work problem Pin
Ravi Bhavnani7-May-15 8:57
professionalRavi Bhavnani7-May-15 8:57 
NewsArticle updated Pin
Ravi Bhavnani5-May-15 9:32
professionalRavi Bhavnani5-May-15 9:32 
GeneralRe: Article updated Pin
ichbinvinh5-May-15 22:48
ichbinvinh5-May-15 22:48 
GeneralRe: Article updated Pin
temuraru7-May-15 23:27
temuraru7-May-15 23:27 
GeneralRe: Article updated Pin
Ravi Bhavnani8-May-15 11:25
professionalRavi Bhavnani8-May-15 11:25 
NewsNew version coming soon Pin
Ravi Bhavnani4-May-15 6:08
professionalRavi Bhavnani4-May-15 6:08 
QuestionTranslator Not working Pin
Member 111126691-May-15 19:15
Member 111126691-May-15 19:15 

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

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