Home > Uncategorized > Yandex Translation in C#

Yandex Translation in C#

Ever since Google started charging for it’s Translation API, and Microsoft put a 2 Million character limit on their free translation API, then you have to start looking outside of the USA for a free translation service. That’s when I discovered the Russian translation service provided by Yandex. They also do plenty of other languages, (Albanian Armenian Azerbaijani Belarusian Bulgarian Catalan Croatian Czech Danish Dutch Estonian Finnish French German Greek Hungarian Italian Latvian Lithuanian Macedonian Norwegian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swedish Turkish Ukrainian)

So, the first step is to go to http://api.yandex.com/translate/ and sign up for a Yandex Passport, and get an API key.

Then, I created a C# class with a static method to do the translation from code:

public static string Translate(string word, string language)
{
string strUrl = “https://translate.yandex.net/api/v1.5/tr.json/translate?”;
strUrl += “key=trnsl.1.1……..”;
strUrl += “&lang=en-” + language;
strUrl += “&text=” + word;
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
string strJson = wc.DownloadString(strUrl);
….
}

This returns a JSON string in the format:

{
“code”: 200,
“lang”: “en-ru”,
“text”: [
“Быть или не быть?”,
“Вот в чем вопрос.”
]
}

So, to de-serialize this to a C# object, I used a class generated from http://json2csharp.com/ as follows:

public class RootObject
{
public int code { get; set; }
public string lang { get; set; }
public List<string> text { get; set; }
}

Then the de-serialization can take place at the end of the translate method:

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
RootObject ro = js.Deserialize<RootObject>(strJson);
return ro.text[0];

A quirk I noticed when doing this as a console app, was that the console could not write our Cyrillic characters. There is a way around this by using the Windows API, but I just used a MessageBox.

Advertisements
Categories: Uncategorized
  1. August 30, 2013 at 2:44 pm

    Unfortunately…. I’ve just realised that Yandex have a 10,000 call per day limit…

  2. September 6, 2013 at 11:31 am

    An alternative (unofficial) calling mechanism to Yandex translate is http://translate.yandex.net/tr.json/translate?lang=en-pl&text=hello&srv=tr-text

    I’m testing if it has the same limitations….

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: