中英文自动翻译(有道翻译、彩云小译)

一.有道翻译

1)获取应用ID 和 应用密钥 

      https://ai.youdao.com/doc.s#guide

2)遵循接口参数接入

    具体参考接口文档:https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
中英文自动翻译(有道翻译、彩云小译)_第1张图片

3)代码如下:

      import $ from "jquery";

      const CryptoJS = require("crypto-js"); // 引用AES源码js

      var appKey = "您的appKey";
      var key = "您的appSecret"; //注意:暴露appSecret,有被盗用造成损失的风险
      var salt = new Date().getTime();
      var curtime = Math.round(new Date().getTime() / 1000);
      var query = this.form.content;
      // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
      var from = "zh-CHS";
      var to = "en";
      var str1 = appKey + this.truncate(query) + salt + curtime + key;
      var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
      //判断是中译英还是英译中
      if (/[\u4E00-\u9FA5]/g.test(this.form.content)) {
        from = "zh-CHS";
        to = "en";
      } else {
        from = "en";
        to = "zh-CHS";
      }
      let contdata = this.form.content

      let params = {
        q: contdata,
        appKey: appKey,
        salt: salt,
        from: from,
        to: to,
        sign: sign,
        signType: "v3",
        curtime: curtime
      };
      let that = this;

      $.ajax({
        url: "http://openapi.youdao.com/api",
        type: "post",
        dataType: "jsonp",
        data: params,
        success: function(data) {
          console.log(data)
          that.$set(that.form, "translate", data.translation[0]);
        },
        error: function(error) {
          console.log(error);
        }
      });
truncate(q) {
      var len = q.length;
      if (len <= 20) return q;
      return q.substring(0, 10) + len + q.substring(len - 10, len);
}

参数较多,且需要计算,较繁琐;并且翻译文本不宜过长。

二.彩云小译

1)登陆彩云科技开放平台获取token(需要审核,较快,10分钟左右)

     https://dashboard.caiyunapp.com/user/sign_in/

2)代码如下:

      let isType = "zh2en";
      let that = this;
      //判断是中译英还是英译中
      if (/[\u4E00-\u9FA5]/g.test(this.form.content)) {
        isType = "zh2en";
      } else {
        isType = "en2zh";
      }
      let payload = {
        source: this.form.content,
        detect: "true",
        trans_type: isType,
        request_id: "demo"
      };
      $.ajax({
        url: "http://api.interpreter.caiyunai.com/v1/translator",
        type: "post",
        data: JSON.stringify(payload),
        headers: {
          "content-type": "application/json",
          "x-authorization": "token " + "您申请的token"
        },
        success: function(data) {
          that.transLoading = false;
          that.$set(that.form, "translate", data.target);
        },
        error: function(error) {
          that.transLoading = false;
          that.$message.error('翻译失败');
          console.log(error);
        }
      });

 

你可能感兴趣的:(自动翻译,javascript)