我正在按照1的要求进行工作,其中我给出一组英语单词,这些单词将以数组格式作为输入,而输出将是西班牙语和法语中的相应元素
例如:
输入:
["One", "Two", "Three"]
["One", "french translate One "," Spanish translate One "]
["Two","french translate Two "," Spanish translate Two "]
我们如何使用使用JavaScript的Google Translation API来实现这一目标。 请指教
答案 0 :(得分:0)
根据Google Cloud Translate API FAQ page,您只能设置一种目标语言。但是,您可以解决。通过对每种目标语言进行单独的API调用并将结果放置在数组中,可以使其工作。
这是我根据APIs documentation针对Node JS提出的解决方案的示例:
const Translate = require('@google-cloud/translate');
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';
// Instantiates a client
const translate = new Translate({
projectId: projectId,
});
//Targated languages
var targets = ['fr','es'];
var result = [];
var word;
//Recursive function
var targetLanguage = function(x)
{
if(x < targets.length)
{
translate
.translate(word, targets[x])
.then(results => {
const translation = results[0];
result.push(`${translation}`);
//Calling the function for the next target language.
targetLanguage(x+1);
})
.catch(err => {
console.error('ERROR:', err);
});
}
else
{
console.log(result);
result = [];
}
}
//Function that takes the word to be translated
function translateWord(originalWord)
{
word = originalWord;
result.push(word);
targetLanguage(0);
}
//Calling the function
translateWord("One");