Python 调用谷歌翻译(2021年3月测试可用)

前言

把之前的用来谷歌翻译的Python文件整理了下,
用来处理翻译下i18n.js所需要的字典,
直接调用即可。

2021年3月测试可用 (¦3[▓▓] 

环境

Python版本: Python 3.7
Python第三方库:PyExecJS

安装

pip3 install PyExecJS

使用

python3 translate.py

代码

translate.py

# -*- coding: utf-8 -*-

import urllib.request
import execjs


class Py4Js():

    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 open_url(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
    req = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(req)
    data = response.read().decode('utf-8')
    return data


# old_language_code = "zh-CN"
# old_language_code = "en"  # 英语
# new_language_code = "de"  # 德语
def translate(content, tk, old_language_code="en", new_language_code="de"):
    if len(content) > 4891:
        print("翻译的长度超过限制!!!")
        return

    content = urllib.parse.quote(content)

    # old_language_code = "zh-CN"
    # old_language_code = "en"  # 英语
    # new_language_code = "de"  # 德语
    url = "https://translate.google.cn/translate_a/single?client=webapp&" \
          "sl=%s&tl=%s&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&clearbtn=1&otf=1&" \
          "pc=1&ssel=3&tsel=3&kc=2&tk=%s&q=%s" % (old_language_code, new_language_code, tk, content)

    result = open_url(url)

    end = result.find("\",")
    if end > 4:
        # print(result[4:end])
        return result[4:end]


"""
 old_language_code = "zh-CN"
 old_language_code = "en"  # 英语
 new_language_code = "de"  # 德语
 默认 英语 翻译为 德语, 可根据自己需要自己改 
"""


def translate_a_word(content, ori_language="en", new_language="de"):
    js = Py4Js()
    tk = js.getTk(content)
    value = translate(content, tk, old_language_code=ori_language, new_language_code=new_language)
    return value


def translate_a_dict(content_dict, ori_language="en", new_language="de"):
    js = Py4Js()
    new_dict = {}
    for key, value in content_dict.items():
        content = value
        tk = js.getTk(value)
        result = translate(content, tk, old_language_code=ori_language, new_language_code=new_language)
        new_dict[key] = result
    return new_dict


"""
 old_language_code = "zh-CN"
 old_language_code = "en"  # 英语
 new_language_code = "de"  # 德语
 默认 英语 翻译为 德语, 可根据自己需要自己改 
"""
if __name__ == "__main__":
    # 翻译一个单词
    ori_word = "Dashboard"
    new_word = translate_a_word(ori_word, ori_language="en", new_language="de")
    print("ori_word", ori_word)
    print("new_word", new_word)

    # 翻译一个字典
    ori_dict = {"数据面板": "Dashboard"}
    new_dict = translate_a_dict(ori_dict, ori_language="en", new_language="de")
    print("ori_dict", ori_dict)
    print("new_dict", new_dict)

其他

如有问题欢迎提出
如有作用请记得留言(留下使用时间即可,方便如果失效了提醒下后来的人)

2021年3月2日17:09:30 测试可用

  • 1
    点赞
  • 0
    评论
  • 8
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏

hyh123a

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者