How to translate text automatically by using Google Translate API (C# 2012)

First you need to install Google.Apis.Translate.v2 Client Library by using Nuget. You can find the instructions here. Then, the basic code is the following:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Threading.Tasks;

using System.IO;

using Google.Apis.Services;
using Google.Apis.Translate.v2;
using Google.Apis.Translate.v2.Data;
using TranslationsResource = Google.Apis.Translate.v2.Data.TranslationsResource;

private async Task Run()
{
   // Create the translation service.
	var service = new TranslateService(new BaseClientService.Initializer()
	{
		ApiKey = "", // your API key, that you get from Google Developer Console
		ApplicationName = "" // your application name, that you get form Google Developer Console
	});
		
	
    String text_to_translate = "Hello!";	
    String target_language_shortname = "fr";
	
    string[] srcText = new[] { text_to_translate };
    var response = await service.Translations.List(srcText, target_language_shortname).ExecuteAsync();
    String translated_text = response.Translations[0].TranslatedText;
}

[STAThread]
static void Main(string[] args)
{

	Console.WriteLine("Translating...");

	try
	{
		new Program().Run().Wait();
	}
	catch (AggregateException ex)
	{
		foreach (var e in ex.InnerExceptions)
		{
			Console.WriteLine("ERROR: " + e.Message);
		}
	}

	Console.WriteLine("Done");
	Console.ReadKey();

}

On top of this, you might want to process and to further improve the output you receive from Google Translate. A few suggestions are:

        static void process_translation(ref String s)
        {
            s = System.Web.HttpUtility.HtmlDecode(s);
            s = s.Replace("_", " ");
            s = s.Replace(" ,", ",");
            s = s.Replace(" .", ".");

            s = s.Replace(" /", "/"); s = s.Replace("/ ", "/");
            s = s.Replace("“ ", "“"); s = s.Replace(" ”", "”");
            s = s.Replace("( ", "("); s = s.Replace(" )", ")");
            s = s.Replace("# ", "#"); s = s.Replace(" #", "#");
            s = s.Replace(" '", "'"); s = s.Replace("' ", "'");

            s = s.Replace("??", ""); // remove ??, a Google Translate bug

            s = s.Replace("«", "\""); s = s.Replace("»", "\"");

            process_quotationmarks(ref s);

            // normal quotation marks
            s = s.Replace("\"-", "\" -"); // "- to " -
            s = s.Replace("-\"", "- \""); // -" to - "

            s = s.Replace("\"–", "\" –"); // "- to " –
            s = s.Replace("–\"", "– \""); // –" to - "

            // left quotation marks
            s = s.Replace("“-", "“ -"); // “- to “ -
            s = s.Replace("-“", "- “"); // -“ to - “

            s = s.Replace("“–", "“ –"); // “- to “ –
            s = s.Replace("–“", "– “"); // –" to - “

            // right quotation marks
            s = s.Replace("”-", "” -"); // ”- to ” -
            s = s.Replace("-”", "- ”"); // -” to - ”

            s = s.Replace("”–", "” –"); // ”- to ” –
            s = s.Replace("–”", "– ”"); // –” to - ”

            /*
            // Japanese
            s = s.Replace("、 ", "、"); s = s.Replace(" 、", "、");
            s = s.Replace("。 ", "。"); s = s.Replace(" 。", "。");
            */
        }

Note that for the above you need to include System.Web as a reference. I would also recommend to process the text you receive using:

static void process_quotationmarks(ref String s)
        {
            int no_qm = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == '\"') no_qm++;
                if (s[i] == '“') no_qm++;
                if (s[i] == '”') no_qm++;
                if (s[i] == '«') no_qm++;
                if (s[i] == '»') no_qm++;

            }
            if (no_qm % 2 == 0) // process quotation mark only if there is an even number of them in the description
            {
                s = s.Replace(" \"", "\""); s = s.Replace("\" ", "\"");
                int left_or_right = -1;
                for (int i = 0; i < s.Length; i++)
                {
                    if (s[i] == '\"')
                    {
                        if (left_or_right == -1) // put a space to the left
                        {
                            if (i > 0) // the description does not begin with "
                            {
                                if ((is_newline_char(s[i - 1]) == false) && (s[i - 1] != ' ')) // the line does not begin with "
                                {
                                    s = s.Insert(i, " ");
                                    i++;
                                }
                            }
                        }
                        else // put a space to the right
                        {
                            if (i < s.Length - 1) // if the document the not end with "
                            {
                                if (is_newline_char(s[i + 1]) == false) // if the line does not end with "
                                {
                                    if (Char.IsLetter(s[i + 1]) || Char.IsDigit(s[i + 1])) // if the next character is a letter or digit
                                    {
                                        s = s.Insert(i + 1, " ");
                                    }
                                }
                            }
                        }
                        left_or_right = left_or_right * -1;
                    }
                    if ((s[i] == '«') || (s[i] == '»')) left_or_right = left_or_right * -1;
                }
                s = s.Replace("\"( ", "\" (");
                s = s.Replace("( \"", "(\"");
                s = s.Replace("\"(", "\" (");
            }
        }

And last but not least:

static void process_dash(ref String s)
{
	s = s.Replace(" -", "-"); s = s.Replace("- ", "-");
	s.Replace(" –", "–"); s = s.Replace("– ", "–");
}

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close