translator.py
# -*- coding: utf-8 -*-
# author: inspurer(月小水长)
# pc_type lenovo
# create_time: 2019/4/6 15:44
# file_name: translator.py
# github https://github.com/inspurer
# qq邮箱 2391527690@qq.com
# 微信公众号 月小水长(ID: inspurer)
import requests
from HandleJs import Py4Js
import win32clipboard as w
import win32con
import time
def getText():#读取剪切板
# 打开剪贴板
w.OpenClipboard()
# 读取剪贴板的内容
d = w.GetClipboardData(win32con.CF_TEXT)
# 关闭剪贴板
w.CloseClipboard()
try:
return d.decode("utf-8")
except:
return d.decode("gbk")
def setText(aString):#写入剪切板
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardText(aString)
w.CloseClipboard()
def translate(tk, content):
if len(content) > 4891:
print("翻译的长度超过限制!!!")
return
param = {"tk": tk, "q": content}
result = requests.get("""http://translate.google.cn/translate_a/single?client=t&sl=en
&tl=zh-CN&hl=zh-CN&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""", params=param)
data = result.json()
# print(data)
print(data[0][0][0])
print(data[0][1][2])
return data[0][0][0]
def main():
js = Py4Js()
ls = ""
while(True):
# 如果剪贴板正在被占用
try:
cs = getText()
except:
time.sleep(1)
cs = getText()
print("cs",cs)
if cs and cs != ls:
print("准备翻译")
content = getText()
tk = js.getTk(content)
res = translate(tk, content)
setText(res)
time.sleep(1)
ls = res
if __name__ == "__main__":
main()
# i am a girl
# i am a boy
HandleJs.py
# -*- coding: utf-8 -*-
# author: inspurer(月小水长)
# pc_type lenovo
# create_time: 2019/4/6 15:49
# file_name: HandleJs.py
# github https://github.com/inspurer
# qq邮箱 2391527690@qq.com
# 微信公众号 月小水长(ID: inspurer)
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)