用python
实现,调用了百度翻译和金山词霸的接口
baidu_translate.py
百度翻译实现
# -*- coding:utf-8 -*-
import time
from urllib import parse
import hashlib
import requests
class BaiduTranslate(object):
def __init__(self):
self.appid = '百度开发者appid'
self.key = '百度开发者appkey'
self.url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
self.headers = {
'Content-Type': 'application/x-www-from-urlencoded'
}
def get_sign(self, q, salt):
str1 = self.appid + q + salt + self.key
sign = hashlib.md5(str1.encode('utf-8')).hexdigest()
return sign
def do_translate(self, q, type_=0):
"""q: 待翻译字符;
type_: 翻译类型。0 表示英文转中文,1 表示中文转英文, 2 表示自动选择"""
lang_list = [('en', 'zh'), ('zh', 'en'), ('auto', 'auto')]
from_lang, to_lang = lang_list[type_]
salt = str(round(time.time()))
sign = self.get_sign(q, salt)
params = {
'q': q,
'from': from_lang,
'to': to_lang,
'appid': self.appid,
'salt': salt,
'sign': sign
}
result = self.send_req(self.url, params)
translate_result = self.process(result)
return translate_result
@staticmethod
def process(result_json):
ret = result_json
if 'error_code' not in result_json:
result = result_json['trans_result']
ret = result[0]['dst']
return ret
def send_req(self, url, params):
"""发送请求,返回结果 json"""
req = requests.post(url, params=params, headers=self.headers)
res = req.json()
return res
if __name__ == '__main__':
word = 'tear'
type_ = 0
tl = BaiduTranslate()
data = tl.do_translate(word, type_)
print(data)
jinshan_translate.py
金山词霸接口实现
# -*- coding:utf-8 -*-
"""
使用金山词霸接口实现翻译
"""
import requests
from urllib import parse
class JinshanTranslate(object):
def __init__(self):
self.base_url = 'https://dict-mobile.iciba.com/interface/index.php'
self.params = {
'c': 'word',
'm': 'getsuggest',
'is_need_mean': 0
}
def do_translate(self, q, type_=None):
"""q 是待翻译的词语,可以是英语也可以是中文。
type_ 没有用,是为了跟百度的翻译接口保持一致"""
self.params['word'] = q
url = self.base_url + '?' + parse.urlencode(self.params)
req = requests.get(url)
res = req.json()
ret = '(无结果)'
if res['status'] != 1:
ret = res
elif res['message']:
key = res['message'][0]['key']
paraphrase = res['message'][0]['paraphrase']
if key != key:
ret = f'({key}) {paraphrase}'
else:
ret = paraphrase
return ret
if __name__ == '__main__':
translator = JinsanTranslate()
result = translator.do_translate('tear')
print(result)
整合两个,以实现同时获取两个接口的翻译
translator.py
# -*- coding:utf-8 -*-
import os
import sys
from baidu_translate import BaiduTranslate
from jinshan_translate import JinshanTranslate
class Translation(object):
def __init__(self, translate_object):
self.translator = translate_object()
def translate(self, q, type_=0):
"""Call do_translate method"""
ret = self.translator.do_translate(q, type_)
return ret
if __name__ == '__main__':
argvs = sys.argv
word = ''
type_ = 0
if len(argvs) < 2:
print('参数不足,需要输入待翻译的字符')
elif len(argvs) == 2:
word = argvs[1]
else:
word, type_ = argvs[1:3]
type_ = int(type_)
t1 = Translation(BaiduTranslate)
data1 = t1.translate(word, type_)
# 保存到本地文件
log_file_path = os.path.join(os.path.dirname(sys.argv[0]), 'query_log.log')
log_file = open(log_file_path, 'a', encoding='utf-8')
log_file.write('\n')
log_file.write('-'*60)
print(f'待翻译词语: {word}')
print()
print(f'百度翻译结果: {data1}')
log_file.write(f'\n{word}: {data1}\n')
log_file.flush()
t2 = Translation(JinshanTranslate)
data2 = t2.translate(word)
print(f'金山词霸结果:{data2}')
log_file.write(f'{word}: {data2}')
log_file.close()
使用命令:
# python translator.py文件路径 待翻译单词
# 如下:
python3 /mnt/e/temp/Translation/translator.py tear
为前面的命令设置一个别名,编辑 ~/.bashrc 文件,添加
alias trans='python3 /mnt/e/code/python/Translation/translator.py'
执行 source ~/.bashrc
使其生效,就可以使用 trans 单词
的格式来执行翻译,如下:
trans tear
结果如下: