1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import requests import random import json from hashlib import md5 import time
appid = '2222222222222222' appkey = 'ooooooooooooooooooo'
def make_md5(s, encoding='utf-8'): return md5(s.encode(encoding)).hexdigest()
def baidu(en_txt=''): salt = random.randint(32768, 65536) sign = make_md5(appid + en_txt + str(salt) + appkey)
api_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate' headers = {'Content-Type': 'application/x-www-form-urlencoded'} payload = {'appid': appid, 'q': en_txt, 'from': 'en', 'to': 'zh', 'salt': salt, 'sign': sign}
res = requests.get(api_url, params=payload, headers=headers, timeout=3.0).json() time.sleep(3.0)
if 'trans_result' in res.keys(): zh_txt = ''.join([seq['dst'] for seq in res['trans_result']]) print(f'*** {en_txt} \n--> {zh_txt}') return zh_txt
if 'error_code' in res.keys(): print(f'*** {en_txt} \n??? {res}')
en_txt = 'so we beat on, boats against the current, borne back ceaselessly into the past.' baidu(en_txt)
|