这是一个自动翻译剪切板内容的程序,它可以读取剪切板内容,然后分句多次进行谷歌翻译,最后将翻译的结果写会剪切板。可以配合autohotkey使用,按下^t时复制选中文本,同时启动翻译剪切板程序

 

写好的程序可以配合https://www.cnblogs.com/jkn1234/p/9672957.html 进行打包

写本程序使用到的参考资料

没有使用到的参考资料 

'''
    这是一个自动翻译剪切板内容的程序
    它可以读取剪切板内容,然后分句多次进行谷歌翻译,最后将翻译的结果写会剪切板
    可以配合autohotkey使用,按下^t时复制选中文本,同时启动翻译剪切板程序
'''
import json
import execjs  # 需要先用pip install PyExecJS安装,用来执行js脚本
import requests
import pyperclip
import re
import copy

# 这个类提供了getTk函数
# 功能是根据待翻译的内容计算相应的Google翻译api里面的tk参数。
# tk参数是浮点数
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翻译api的函数。主要是tk参数和q参数
# text是待翻译的内容
# tk是根据待翻译的内容生成的一个浮点数作为api里面的tk参数
def buildUrl(text, tk):
    baseUrl = 'https://translate.google.cn/translate_a/single'
    baseUrl += '?client=t&'
    baseUrl += 's1=auto&'
    baseUrl += 't1=zh-CN&'
    baseUrl += 'h1=zh-CN&'
    baseUrl += 'dt=at&'
    baseUrl += 'dt=bd&'
    baseUrl += 'dt=ex&'
    baseUrl += 'dt=ld&'
    baseUrl += 'dt=md&'
    baseUrl += 'dt=qca&'
    baseUrl += 'dt=rw&'
    baseUrl += 'dt=rm&'
    baseUrl += 'dt=ss&'
    baseUrl += 'dt=t&'
    baseUrl += 'ie=UTF-8&'
    baseUrl += 'oe=UTF-8&'
    baseUrl += 'otf=1&'
    baseUrl += 'pc=1&'
    baseUrl += 'ssel=0&'
    baseUrl += 'tsel=0&'
    baseUrl += 'kc=2&'
    baseUrl += 'tk=' + str(tk) + '&'

    # url中由%数字替换一些特殊的字符
    text = text.replace('+', '%2B')
    text = text.replace('&', '%26')
    text = text.replace('#', '%23')

    baseUrl += 'q=' + text
    return baseUrl

# 将text里面的文本翻译成中文,并返回
# text里面的语言是自动检测的,可以是英语、日语、德语等任何语言
def translate(text):
    header = {
        'authority': 'translate.google.cn',
        'method': 'GET',
        'path': '',
        'scheme': 'https',
        'accept': '*/*',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie': '',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
        'x-client-data': 'CIa2yQEIpbbJAQjBtskBCPqcygEIqZ3KAQioo8oBGJGjygE='
    }
    url = buildUrl(text, js.getTk(text))
    res = ''
    try:
        r = requests.get(url)
        result = json.loads(r.text)
        if result[7] != None:
            # 如果我们文本输错,提示你是不是要找xxx的话,那么重新把xxx正确的翻译之后返回 ?
            try:
                correctText = result[7][0].replace('<b><i>', ' ').replace('</i></b>', '')
                print(correctText)
                correctUrl = buildUrl(correctText, js.getTk(correctText))
                correctR = requests.get(correctUrl)
                newResult = json.loads(correctR.text)
                res = newResult[0][0][0]
            except Exception as e:
                print(e)
                res = result[0][0][0]

        else:
            i = 0
            while result[0][i][0] != None:
                res += result[0][i][0]
                i += 1
    except Exception as e:
        res = ''
        print(url)
        print("翻译" + text + "失败")
        print("错误信息:")
        print(e)
    finally:
        return res
if __name__ == '__main__':
    t0 = str(pyperclip.paste()) # t0存放剪切板的内容

    # 将所有的.;?全部替换为英文的','防止一行的句子翻译到英文句子结束符号时就不翻译了.
    # 注意最好不要替换为中文符号,
    # 因为谷歌翻译时会用英文的标点符号进行断句,中文的符号起不到这个作用
    t0 = t0.replace('.', ',')
    t0 = t0.replace(';', ',')
    t0 = t0.replace('?', ',')
    t0 = t0.split("\r\n")# 按行分割句子

    # 翻译t5中的每一个句子,将翻译好的句子用'\r\n'连接后放入combine
    combine = ''
    js = Py4Js()
    for i in t0:
        temp = copy.deepcopy(i)
        res = translate(temp) # SendInput and SendPlay
        combine = combine + res + '\r\n'

    print(combine)
    pyperclip.copy(combine)# 将翻译好的结果放入剪切板

    # js = Py4Js()
    # print("Yes, Removing pyinstaller and reinstalling with pip install git add git://github.com/pyinstaller/pyinstaller@develop as well as including PyQt5.sip in my hiddenimports fixed the issue.")  # SendInput and SendPlay
    # res = translate("Quora is a simple question-and-answer site。 Whatever your question, type it in the search box and, if there isn't already an answer there, users will pile in and attempt to answer it。 Information is organised more like Wikipedia than Google, with answers prioritised by how useful they are, but the site uses Twitter-style following to track the best contributors.") # SendInput and SendPlay
    # print(res)

 

posted on 2018-09-19 10:15  jkn1234  阅读(1553)  评论(0编辑  收藏  举报