(七)Python3 实现不限字符的谷歌翻译方法

如果要对网页正文进行翻译,可直接参考:https://blog.csdn.net/qq_42632840/article/details/101938081

谷歌翻译介绍

谷歌翻译网址:https://translate.google.cn/

Google 翻译是谷歌公司提供一项免费的翻译服务,可提供103 种语言之间的即时翻译,支持任意两种语言之间的字词、句子和网页翻译。

实现谷歌翻译的方法

经过查找资料,python实现谷歌翻译大概有三类方法:
1.使用google API
此方法需要付费,然后绑定项目和google账号,启动API,创建service account,具体可见:https://blog.csdn.net/nicolelili1/article/details/76973097

2.使用别人已经封装好的一些库
3.通过爬虫实现翻译,本文主要实现这方法

通过爬虫实现谷歌翻译

首先给出代码:
Py4Js.py:

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)

google_trans.py:

from Py4Js import *
import requests

# 谷歌翻译方法
def google_translate(content):
    '''实现谷歌的翻译'''
    res_trans=""
    # print(js)
    if len(content)>4891:
        while len(content) > 4891:
            #print("翻译的长度超过限制!!!")
            # temp=content[0:4000-len(content[0:4000].split('.')[-1])]+content[4000].split('.')[0]
            # content=content[4001-len(content[0:4000].split('.')[-1]):]
            temp=content[0:4889]
            content=content[4890:]
            print(content+"\n\n")
            temp_trans=google_trans_final(temp)
            res_trans=res_trans+temp_trans
            #google_translate(content)
            print("实现多次翻译拼接,用这个分割一下\n\n")
            #return
        temp_trans=google_trans_final(content)
        res_trans+=temp_trans
        return res_trans
    else:
        return google_trans_final(content)

def google_trans_final(content):
    js = Py4Js()
    tk = js.getTk(content)
    param = {'tk': tk, 'q': content}
    result = requests.get("http://translate.google.cn/translate_a/single?client=t&sl=auto&tl=en&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1&srcrom=0&ssel=0&tsel=0&kc=2&tk=%s&q=%s"%(tk,content))

    # 返回的结果为Json,解析为一个嵌套列表
    trans = result.json()[0]
    
    ret = ''
    for i in range(len(trans)):
        line = trans[i][0]
        if line != None:
            ret += trans[i][0]

    return ret

问题与解析

1.No module named ‘execjs’

安装execjs即可 pip install PyExecJS

2.部分原理介绍:

Py4Js.py:用于获得tk。
打开google的浏览器,进入翻译界面https://translate.google.cn/,打开开发者模式,观察network,输入翻译内容进行测试,可以发现,带有single?client=web…的url里面有翻译的结果:
在这里插入图片描述
可以看到翻译结果在Response的第一个列表的第一个位置,所以实现翻译只需要获得此url并且获取第一个位置的字符串即可。以下部分代码就是实现获得第一个列表第一个位置的字符串:

for i in range(len(trans)):
        line = trans[i][0]
        if line != None:
            ret += trans[i][0]

关于tk:在google搜索上,基本上不同的翻译内容对应着不同的tk值,而其他的比如翻译语言、翻译结构等参数都几乎相同,比如China对应的tk是942592.574918。有大神破解了tk,即使用js生成对应文本的tk。也有根据node.js实现这个爬虫的,可参考:https://segmentfault.com/a/1190000019152744?utm_source=tag-newest

关于不限字符翻译,在此部分实现不限字符翻译,即分段翻译然后拼接起来:

if len(content)>4891:
        while len(content) > 4891:
            #print("翻译的长度超过限制!!!")
            temp=content[0:4000-len(content[0:4000].split('.')[-1])]+content[4000].split('.')[0]
            content=content[4001-len(content[0:4000].split('.')[-1]):]
            #temp=content[0:4889]
            #content=content[4890:]
            print(content+"\n\n")
            temp_trans=google_trans_final(temp)
            res_trans=res_trans+temp_trans
            #google_translate(content)
            print("实现多次翻译拼接,用这个分割一下\n\n")
            #return

其中4891是经过测试的谷歌稳定翻译的最大字符数。但是此处翻译还有很大的完善空间,对某些语言的翻译效果不好。如果是翻译很长的文本,需要对这部分进行完善,如有建议、改进措施欢迎评论和私信。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章