Python3 Baidu&Google translate via requests lib

翻译API

  1. 百度翻译官方API文档
  2. 申请翻译API服务
    已登录百度账号的用户,点击“立即使用”,注册成为开发者,即可获得APPID和密钥信息;同一个账户或手机号码仅能申请一组APPID和密钥信息,该APPID和密钥信息可用于多项服务调用。
  3. 不同于Baidu直接给出API, Google翻译需要调用其封装的lib, 所以google翻译的原理是模拟浏览器中Google翻译的URL请求

Python requests

  1. requests是Python的一个优雅而简单的HTTP库,使用友好, 封装完善.
    支持Python 2.7 & 3.4–3.7及PyPy
  2. 基于urllib3的封装
    1. Requests: HTTP for Humans™
    2. Requests quickstart

Source code

Git repositories

Source Code at github

Baidu

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hashlib
import random
import json
import requests

print('translate begin...')

# set baidu develop parameter
apiurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
appid = '20180816000194959'
secretKey = 'lWzwUiWmhRORknf68FCT'

#翻译内容 源语言 翻译后的语言
def translateBaidu(content, fromLang = 'en', toLang = 'zh'):
    salt = str(random.randint(32768, 65536))
    sign = appid + content + salt + secretKey
    sign = hashlib.md5(sign.encode("utf-8")).hexdigest()

    try:
        paramas = {
            'appid': appid,
            'q': content,
            'from': fromLang,
            'to': toLang,
            'salt': salt,
            'sign': sign
            }
        response = requests.get(apiurl, paramas)
        jsonResponse = response.json()  # 获得返回的结果,结果为json格式
        dst = str(jsonResponse["trans_result"]
                  [0]["dst"])  # 取得翻译后的文本结果
        return dst
    except Exception as e:
        print(e)
if __name__ == '__main__':
    print(translateBaidu('Chunchun is lovely and so sweet heart. '))
    print(translateBaidu('于千万人之中遇见你所要遇见的人,于千万年之中,时间的无涯的荒野里,没有早一步,也没有晚一步,刚巧牵起你的手',
    'zh','en'))

print('ending...')

'''
# out put 
Chunchun是如此可爱,如此甜蜜的心。
Meet the person you want to meet among millions of people. In the endless wilderness of time, in the
course of millions of years, neither earlier nor later, just take your hand.
'''

Google

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests # pip install requests
import json
import execjs  # pip install PyExecJS
import urllib3  # pip install urllib3

'''
author by Benji 
date at 2018.12.07

实现: 模拟浏览器中Google翻译的url请求
    不同于Baidu直接给出API, Google翻译需要调用其封装的lib

参考:   https://www.jianshu.com/p/95cf6e73d6ee
        https://cloud.google.com/translate/docs/apis

'''

class PyJsParams():
    def __init__(self):
        self.ctx = execjs.compile("""
        function TL(a) {
        var k = "";
        var b = 406644;
        var b1 = 3293161072;
        var jd = ".";
        var $b = "+-a^+6";
        var Zb = "+-3^+b+-f";
        for (var e = [], f = 0, g = 0; g < a.length; g++) {
            var m = a.charCodeAt(g);
            128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
            e[f++] = m >> 18 | 240,
            e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
            e[f++] = m >> 6 & 63 | 128),
            e[f++] = m & 63 | 128)
        }
        a = b;
        for (f = 0; f < e.length; f++) a += e[f],
        a = RL(a, $b);
        a = RL(a, Zb);
        a ^= b1 || 0;
        0 > a && (a = (a & 2147483647) + 2147483648);
        a %= 1E6;
        return a.toString() + jd + (a ^ b)
    };
    function RL(a, b) {
        var t = "a";
        var Yb = "+";
        for (var c = 0; c < b.length - 2; c += 3) {
            var d = b.charAt(c + 2),
            d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
            d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
            a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
        }
        return a
    }
    """)

    def getTk(self, text):
        return self.ctx.call("TL", text)


def buildUrl(text, tk):
    baseUrl = 'https://translate.google.com/translate_a/single?client=webapp&'
    baseUrl += '&sl=auto&tl=' + toLang
    baseUrl += '&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&'
    baseUrl += 'tk='+str(tk)+'&'
    baseUrl += 'q='+text
    return baseUrl


def translate(text, jsParas):
    url = buildUrl(text, jsParas.getTk(text))
    try:
        # 添加headers, 模仿浏览器行为
        headers = requests.utils.default_headers()
        headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
        # https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
        urllib3.disable_warnings()
        # solve: SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
        r = requests.get(url, headers=headers, verify=False)
        result = json.loads(r.text)  
        res = str(result[0][0][0])
    except Exception as e:
        res = ''
        print("翻译"+text+"失败")
        print("错误信息:")
        print(e)
    finally:
        return res

toLang = 'en'

if __name__ == '__main__':
    jsParas = PyJsParams()
    res = translate('小顺子给Chunchun娘娘请安了', jsParas)
    print(res)
    
'''
output
Xiaoshun gave the Chunchun girl an appointment.
'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值