在C#中使用Google翻译API

目录

介绍

要求

示例翻译函数

兴趣点


介绍

我们想轻松地将文本字符串翻译成另一种语言。从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<List<dynamic>>(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(请求过多)错误。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值