赞
踩
该程序为翻译软件,支持百度翻译、有道翻译、谷歌翻译三种翻译方式。用户输入需要翻译的文本,选择翻译方式(按钮),点击“翻译”按钮即可在下方显示翻译结果。程序使用Python编写,GUI使用PyQt5库,涉及到了requests、js2py等第三方库的使用,具有一定的技术难度。
- '''
- Function:
- 翻译软件V0.1.2,支持:
- --百度翻译
- --有道翻译
- --谷歌翻译
- '''
- import re
- import js
- import sys
- import time
- import js2py
- import random
- import hashlib
- import requests
- from PyQt5.QtGui import *
- from PyQt5.QtWidgets import *
-
-
- '''百度翻译类'''
- class baidu():
- def __init__(self):
- self.session = requests.Session()
- self.session.cookies.set('BAIDUID', '19288887A223954909730262637D1DEB:FG=1;')
- self.session.cookies.set('PSTM', '%d;' % int(time.time()))
- self.headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
- }
- self.data = {
- 'from': '',
- 'to': '',
- 'query': '',
- 'transtype': 'translang',
- 'simple_means_flag': '3',
- 'sign': '',
- 'token': '',
- 'domain': 'common'
- }
- self.url = 'https://fanyi.baidu.com/v2transapi'
- self.langdetect_url = 'https://fanyi.baidu.com/langdetect'
- def translate(self, word):
- self.data['from'] = self.detectLanguage(word)
- self.data['to'] = 'en' if self.data['from'] == 'zh' else 'zh'
- self.data['query'] = word
- self.data['token'], gtk = self.getTokenGtk()
- self.data['token'] = '6482f137ca44f07742b2677f5ffd39e1'
- self.data['sign'] = self.getSign(gtk, word)
- res = self.session.post(self.url, data=self.data)
- return [res.json()['trans_result']['data'][0]['result'][0][1]]
- def getTokenGtk(self):
- url = 'https://fanyi.baidu.com/'
- res = requests.get(url, headers=self.headers)
- token = re.findall(r"token: '(.*?)'", res.text)[0]
- gtk = re.findall(r";window.gtk = ('.*?');", res.text)[0]
- return token, gtk
- def getSign(self, gtk, word):
- evaljs = js2py.EvalJs()
- js_code = js.bd_js_code
- js_code = js_code.replace('null !== i ? i : (i = window[l] || "") || ""', gtk)
- evaljs.execute(js_code)
- sign = evaljs.e(word)
- return sign
- def detectLanguage(self, word):
- data = {
- 'query': word
- }
- res = self.session.post(self.langdetect_url, headers=self.headers, data=data)
- return res.json()['lan']
-
-
- '''有道翻译类'''
- class youdao():
- def __init__(self):
- self.headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
- 'Referer': 'http://fanyi.youdao.com/',
- 'Cookie': 'OUTFOX_SEARCH_USER_ID=-481680322@10.169.0.83;'
- }
- self.data = {
- 'i': None,
- 'from': 'AUTO',
- 'to': 'AUTO',
- 'smartresult': 'dict',
- 'client': 'fanyideskweb',
- 'salt': None,
- 'sign': None,
- 'ts': None,
- 'bv': None,
- 'doctype': 'json',
- 'version': '2.1',
- 'keyfrom': 'fanyi.web',
- 'action': 'FY_BY_REALTlME'
- }
- self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
- def translate(self, word):
- ts = str(int(time.time()*10000))
- salt = ts + str(int(random.random()*10))
- sign = 'fanyideskweb' + word + salt + '97_3(jkMYg@T[KZQmqjTK'
- sign = hashlib.md5(sign.encode('utf-8')).hexdigest()
- bv = '5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
- bv = hashlib.md5(bv.encode('utf-8')).hexdigest()
- self.data['i'] = word
- self.data['salt'] = salt
- self.data['sign'] = sign
- self.data['ts'] = ts
- self.data['bv'] = bv
- res = requests.post(self.url, headers=self.headers, data=self.data)
- return [res.json()['translateResult'][0][0].get('tgt')]
-
-
- '''Google翻译类'''
- class google():
- def __init__(self):
- self.headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
- }
- self.url = 'https://translate.google.cn/translate_a/single?client=t&sl=auto&tl={}&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&tk={}&q={}'
- def translate(self, word):
- if len(word) > 4891:
- raise RuntimeError('The length of word should be less than 4891...')
- languages = ['zh-CN', 'en']
- if not self.isChinese(word):
- target_language = languages[0]
- else:
- target_language = languages[1]
- res = requests.get(self.url.format(target_language, self.getTk(word), word), headers=self.headers)
- return [res.json()[0][0][0]]
- def getTk(self, word):
- evaljs = js2py.EvalJs()
- js_code = js.gg_js_code
- evaljs.execute(js_code)
- tk = evaljs.TL(word)
- return tk
- def isChinese(self, word):
- for w in word:
- if '\u4e00' <= w <= '\u9fa5':
- return True
- return False
-
-
- '''简单的Demo'''
- class Translator(QWidget):
- def __init__(self, parent=None, **kwargs):
- super(Translator, self).__init__(parent)
- self.setWindowTitle('翻译软件')
- self.Label1 = QLabel('原文')
- self.Label2 = QLabel('译文')
- self.LineEdit1 = QLineEdit()
- self.LineEdit2 = QLineEdit()
- self.translateButton1 = QPushButton()
- self.translateButton2 = QPushButton()
- self.translateButton3 = QPushButton()
- self.translateButton1.setText('百度翻译')
- self.translateButton2.setText('有道翻译')
- self.translateButton3.setText('谷歌翻译')
- self.grid = QGridLayout()
- self.grid.setSpacing(12)
- self.grid.addWidget(self.Label1, 1, 0)
- self.grid.addWidget(self.LineEdit1, 1, 1)
- self.grid.addWidget(self.Label2, 2, 0)
- self.grid.addWidget(self.LineEdit2, 2, 1)
- self.grid.addWidget(self.translateButton1, 1, 2)
- self.grid.addWidget(self.translateButton2, 2, 2)
- self.grid.addWidget(self.translateButton3, 3, 2)
- self.setLayout(self.grid)
- self.resize(400, 150)
- self.translateButton1.clicked.connect(lambda : self.translate(api='baidu'))
- self.translateButton2.clicked.connect(lambda : self.translate(api='youdao'))
- self.translateButton3.clicked.connect(lambda : self.translate(api='google'))
- self.bd_translate = baidu()
- self.yd_translate = youdao()
- self.gg_translate = google()
- def translate(self, api='baidu'):
- word = self.LineEdit1.text()
- if not word:
- return
- if api == 'baidu':
- results = self.bd_translate.translate(word)
- elif api == 'youdao':
- results = self.yd_translate.translate(word)
- elif api == 'google':
- results = self.gg_translate.translate(word)
- else:
- raise RuntimeError('Api should be <baidu> or <youdao> or <google>...')
- self.LineEdit2.setText(';'.join(results))
-
-
- '''run'''
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- demo = Translator()
- demo.show()
- sys.exit(app.exec_())
js.py
- bd_js_code = r'''
- function a(r) {
- if (Array.isArray(r)) {
- for (var o = 0, t = Array(r.length); o < r.length; o++)
- t[o] = r[o];
- return t
- }
- return Array.from(r)
- }
- function n(r, o) {
- for (var t = 0; t < o.length - 2; t += 3) {
- var a = o.charAt(t + 2);
- a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a),
- a = "+" === o.charAt(t + 1) ? r >>> a : r << a,
- r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
- }
- return r
- }
- function e(r) {
- var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
- if (null === o) {
- var t = r.length;
- t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr(-10, 10))
- } else {
- for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++)
- "" !== e[C] && f.push.apply(f, a(e[C].split(""))),
- C !== h - 1 && f.push(o[C]);
- var g = f.length;
- g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice(-10).join(""))
- }
- var u = void 0
- , l = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
- u = null !== i ? i : (i = window[l] || "") || "";
- for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
- var A = r.charCodeAt(v);
- 128 > A ? S[c++] = A : (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)),
- S[c++] = A >> 18 | 240,
- S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224,
- S[c++] = A >> 6 & 63 | 128),
- S[c++] = 63 & A | 128)
- }
- for (var p = m, F = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++)
- p += S[b],
- p = n(p, F);
- return p = n(p, D),
- p ^= s,
- 0 > p && (p = (2147483647 & p) + 2147483648),
- p %= 1e6,
- p.toString() + "." + (p ^ m)
- }
- '''
-
-
- gg_js_code = '''
- 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
- }
- '''
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。