目录
介绍
要求
示例翻译函数
兴趣点
介绍我们想轻松地将文本字符串翻译成另一种语言。从Google 翻译API返回的结果非常晦涩。它们采用JSON锯齿状数组的形式。当您必须翻译多个句子时,甚至更加困难。本技巧介绍了如何使用C#正确使用免费API。
要求您必须添加对的System.Web.Extensions引用。然后添加以下using指令:
using System.Net.Http;
using System.Collections;
using System.Web.Script.Serialization;
示例翻译函数
在代码中添加以下函数:
public string TranslateText(string input)
{
// Set the language from/to in the url (or pass it into this function)
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"en", "es", Uri.EscapeUriString(input));
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
// Get all json data
var jsonData = new JavaScriptSerializer().Deserialize(result);
// Extract just the first array element (This is the only data we are interested in)
var translationItems = jsonData[0];
// Translation Data
string translation = "";
// Loop through the collection extracting the translated objects
foreach (object item in translationItems)
{
// Convert the item array to IEnumerable
IEnumerable translationLineObject = item as IEnumerable;
// Convert the IEnumerable translationLineObject to a IEnumerator
IEnumerator translationLineString = translationLineObject.GetEnumerator();
// Get first object in IEnumerator
translationLineString.MoveNext();
// Save its value (translated text)
translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
}
// Remove first blank character
if (translation.Length > 1) { translation = translation.Substring(1); };
// Return translation
return translation;
}
在以下行中设置from/to语言。在这种情况下,en(从语言)和es(到语言):
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"en", "es", Uri.EscapeUriString(input));
然后调用您的代码:
string translatedText = TranslateText(text);
兴趣点
使用免费的API,您每小时只能翻译大约100个单词。如果您滥用此权限,则Google API将返回429(请求过多)错误。