Click here to Skip to main content
11,409,801 members (61,514 online)
Click here to Skip to main content

Language Translator Using Google Translate

, 29 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
We will see with a real sample on how to implement a language translator by using Google Translate.

Introduction

In this article we will see with real code how to implement a language translator.

Note:

  • We are not re-inventing or writing a language translator engine. All we do is screen scraping.
  • We do not make use of Google translation library but instead we make a simple HTTP Post request to “http://translate.google.com/translate_t” with parameters.
  • We will be using HtmlAgilityPack for loading and selecting portion of the HTML document. I.e., the output of the translated language.

You might ask, why don't we make use of the Google Translate API. Here's why I don't want to or you may not like too. I want to implement a simple translator and have no intention to pay for the language translation. Please check the pricing if you really want to use the Google Translate API.

Here's the advantages of this custom code for language translation.

  1. Same code can be used in Phone, Desktop, or Modern UI applications. It comes with code re-usability.
  2. Less dependency and more easy to read and implement code. There's only one 3rd party dependency in this translator, i.e., HTML Agility. We do have various versions and libraries for dedicated platforms so we don't have to worry about HTML Agility dependency.

Background

Knowledge of HTTP WebRequest/Response and C# coding.

Using the code

Below is the code snippet where we create an instance of WebClient and do an Async upload to Google Translator:

static void Main(string[] args)
{
    string content = "Thank You";
    
    // Set the From and To language
    string fromLanguage = "English";
    string toLanguage = "Spanish";

    // Create a Language mapping
    var languageMap = new Dictionary<string, string>();
    InitLanguageMap(languageMap);

    Console.WriteLine("Given Word: " + content);

    // Create an instance of WebClient in order to make the language translation
    Uri address = new Uri("http://translate.google.com/translate_t");
    WebClient wc = new WebClient();
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

    // Async Upload to the specified source
    // i.e http://translate.google.com/translate_t for handling the translation.
    wc.UploadStringAsync(address, 
       GetPostData(languageMap[fromLanguage], languageMap[toLanguage], content));

    Console.ReadLine();
} 

Code snippet for GetPostData:

static string GetPostData(string fromLanguage, string toLanguage, string content)
{
   // Set the language translation. All we need is the language pair, from and to.
   string strPostData = string.Format("hl=en&ie=UTF8&oe=UTF8submit=Translate&langpair={0}|{1}",
                                      fromLanguage,
                                      toLanguage);

   // Encode the content and set the text query string param
   return strPostData += "&text=" + HttpUtility.UrlEncode(content);
}

Below is the code snippet which handles the WebClient Upload Complete.

static void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    if (e.Result != null)
    {
      var doc = new HtmlDocument();
      doc.LoadHtml(e.Result);
      var node = doc.DocumentNode.SelectSingleNode("//span[@id='result_box']");
      var output = node != null ? node.InnerText : e.Error.Message;
      Console.WriteLine("Translated Text: "+output);
   }
}

Points of Interest

It was fun and I never thought it would be that easy to implement the language translator. Hope it might help others in some ways.

I have used some portion of the code, say for language mapping, from Ravi Bhavnani's article. I'm thankful to him. Here's the article link - http://www.codeproject.com/Articles/12711/Google-Translator.

History

  • Version 1.0 - Coded Language Translator Console Project.

License

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

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile

Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

In Brief

Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.

Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF

Software Development

Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI

Healthcare Domain Experience

CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability

Education

B.E (Computer Science)

CodeProject Contest So Far:

1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro

2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics

3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin

4. Intel App Innovation Contest 2013 - eHealthCare

5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014

6. Grand Prize Winner of CodeProject Android Article Contest 2014

7. Grand Prize Winner of IOT on Azure Contest 2015

Comments and Discussions

 
QuestionStill not working. Please help PinmemberPastorBurt212-Mar-15 20:04 
QuestionHow to use translator in vb.net PinmemberMember 1039296321-Feb-15 1:26 
QuestionNo longer working PinmemberMember 1122292710-Nov-14 17:28 
AnswerRe: No longer working Pinmemberakku27-Nov-14 2:06 
AnswerRe: No longer working PinmemberHM India2-Dec-14 7:00 
AnswerRe: No longer working PinmvpRanjan.D2-Dec-14 7:58 
GeneralRe: No longer working PinmemberMember 1116217829-Jan-15 4:44 
GeneralRe: No longer working PinmvpRanjan.D29-Jan-15 4:46 
GeneralRe: No longer working Pinmemberjohn1986_210-Feb-15 10:50 
GeneralRe: No longer working Pinmemberjohn1986_210-Feb-15 10:57 
GeneralRe: No longer working PinmvpRanjan.D10-Feb-15 11:17 
GeneralRe: No longer working Pinmemberjohn1986_217-Feb-15 16:04 
GeneralRe: No longer working PinmvpRanjan.D17-Feb-15 16:36 
QuestionIs there any way to see all the translated lines? PinmemberEcehan Ece20-Apr-14 3:28 
Questiongoogle translator PinmemberMember 1054129528-Feb-14 23:48 
AnswerRe: google translator PinmvpRanjan.D1-Mar-14 5:10 
QuestionTranslation is not working PinmemberAhmedRob19-Feb-14 9:37 
QuestionThank you for Ranjan.D Pinmemberchoi sungbeom27-Jan-14 13:21 
Questionplease open HtmlAgilityPack source Pinmemberchoi sungbeom26-Jan-14 23:05 
AnswerRe: please open HtmlAgilityPack source PinmvpRanjan.D27-Jan-14 5:37 
Question:(( PinmemberPramodParth17-Jan-14 0:51 
QuestionNot support Unicode Character? PinmemberMember 996119531-Aug-13 23:15 
AnswerRe: Not support Unicode Character? PinprofessionalRanjan.D4-Sep-13 5:20 
GeneralRe: Not support Unicode Character? PinmemberMember 99611954-Sep-13 5:55 

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
Web04 | 2.8.150414.5 | Last Updated 29 Aug 2013
Article Copyright 2013 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid