【问题标题】:how to pass format to google cloud translation API using the client library?如何使用客户端库将格式传递给谷歌云翻译 API?
【发布时间】:2018-10-16 04:59:22
【问题描述】:

我们在 express 应用程序中使用google cloud translation API。 我正在尝试使用客户端库进行翻译,而不是每次都发出 API 请求。 1.我想知道的是如何在使用客户端库时将格式(文本或html)等选项传递给api? 我可以通过使用requestjs 像这样发出http请求来实现这一点:

var request = require('request');
var url = 'https://translation.googleapis.com/language/translate/v2';
var options1 = {
  q: 'amore mio',
  target: 'hi',
  format: 'text',
  source: 'it',
  key: 'my API key'
}

request.post({url:url, qs:options1}, (err, res, body)=> {
  if(err) {
    console.log('ERR: ', err);
  }
  console.log('RES: ', res.statusCode);
  console.log('Body: ', body);
})

但使用客户端库的示例仅显示以下内容:

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,
});

// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';

// Translates some text into Russian
translate
  .translate(text, target)
  .then(results => {
    const translation = results[0];

console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);


})
.catch(err => {
        console.error('ERROR:', err);
 });

有没有办法可以使用客户端库传递“格式”等选项?

  1. 如何在第一种方法中将字符串数组传递给选项对象的 q 属性(查询字符串)?如果我直接传递一个数组,例如:

    q: ['amore mio', 'grazie']

我收到一条错误消息:

RES:  400
Body:  {
  "error": {
    "code": 400,
    "message": "Required Text",
    "errors": [
      {
        "message": "Required Text",
        "domain": "global",
        "reason": "required"
      }
    ]
  }
}

【问题讨论】:

    标签: google-translate google-translation-api


    【解决方案1】:

    对于关于传递输入参数数组的问题 2,如果您使用 cURL 发送类似于 this example 的 POST 请求,则此方法可以正常工作。我自己也试过了,很成功。我尝试使用 request 库对来自 snipper 1 的代码进行不同的操作,但似乎 request 库没有正确传递数组。我一般会建议使用client library,它可以成功处理输入文本中的数组。

    【讨论】:

    • 是的,Phil 你是对的,我之前也通过 curl 完成了此操作,它可以工作,但不能满足请求。现在我也将使用客户端库,因为我知道如何传递选项对象,这是我什至查看此方法的唯一原因。感谢您的回复,干杯!
    【解决方案2】:

    好的,经过一番研究,我只是尝试传递带有格式和其他属性(如源语言和目标语言)而不是目标的选项对象,并且它起作用了。 所以这可以通过以下方式实现:

    const options = {
    to: target,
    format: 'html',
    prettyPrint: true
    }
    
    translate
      .translate(text, options)
      .then(results => {
        const translation = results[0];
        console.log('flag: ', Array.isArray(translation));
        console.log(`Text: ${text}`);
        console.log(`Translation: ${translation}`);
      })
      .catch(err => {
        console.error('ERROR:', err);
      });
    

    【讨论】:

      【解决方案3】:

      使用 JSON.stringify

      `https://translation.googleapis.com/language/translate/v2?q=${JSON.stringify([array]}`
      

      【讨论】:

        猜你喜欢
        • 2017-11-11
        • 2018-03-26
        • 1970-01-01
        • 2019-03-05
        • 2020-09-25
        • 2016-03-21
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        相关资源
        最近更新 更多