如何从LanguageApp.translate返回自动检测到的语言? [英] How to return the auto detected language from LanguageApp.translate?

查看:81
本文介绍了如何从LanguageApp.translate返回自动检测到的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个将文本翻译成英语(无论输入哪种语言)的应用程序.翻译工作已经很好,但是现在我试图检测输入的语言,而且我不知道如何从LanguageApp.translate获取检测到的语言.

I´d like to make an application which translates text to english (no matter which language is entered). The translation is already working pretty well, but now i´m trying to detect the language entered and i have no clue how to get the detected language from LanguageApp.translate.

我尝试使用google API,但由于它是付费的,因此我需要一个免费的意见,因为这是一个仅对我而言非商业用途的小项目.

I tried using the google API but as it´s paid i need a opinion which is free as it´s a small project just for me and non commercial.

var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);

指定了

sourceText和targetLang(目标语言).sourceLang是"(空),因此Google翻译会自动检测到它.

sourceText, and targetLang (target Language) are specified. sourceLang is "" (empty), so google translate auto detects it.

我想将检测到的语言添加到返回的字符串中.例如,如果我输入"bonjur",它将返回"hellofr",fr代表法语.

I´d like to add the detected language to the string that gets returned. For example if i enter "bonjur" it returns "hellofr" with fr standing for french.

推荐答案

您可以使用外部api,例如detectlanguage.com.他们的免费帐户每天提供1000个请求.

You can use an external api, for example detectlanguage.com. Their free account offers 1000 requests per day.

// Get your APIkey at https://www.detectlanguage.com
// Replace it in 'yourApiKeyHere'
function detectLanguage(text) {
  var payload = {
    "q": text
  };

  var options = {
    "method"  : "post",
    "payload" : payload,
    "headers" : {
      "Authorization" : "Bearer " + yourApiKeyHere
    }
  };

  var url        = "https://ws.detectlanguage.com/0.2/detect";   
  var response   = UrlFetchApp.fetch(url, options);   

  Logger.log(response.getContentText());
  // response: {"data":{"detections":[{"language":"nl","isReliable":true,"confidence":11}]}}
  return JSON.parse(response.getContentText()).data.detections[0].language;
}

现在在您的代码中使用此

Now use this in your code

// contentType is optional
function translateTo(word, targetLanguage, contentType) {
  return contentType ?
    LanguageApp.translate(word, detectLanguage(word), targetLanguage, {contentType: contentType})
    : LanguageApp.translate(word, detectLanguage(word), targetLanguage);
}

这篇关于如何从LanguageApp.translate返回自动检测到的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆