Last active
April 2, 2018 08:04
-
-
Save zweite/15504929e7506c5c14dff9269a5b7b28 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# 百度翻译 | |
import requests | |
import json | |
import random | |
import md5 | |
import httplib | |
import urllib | |
appid = '' | |
secretKey = '' | |
def transapi(ch): | |
httpClient = None | |
myurl = '/api/trans/vip/translate' | |
q = ch | |
fromLang = 'zh' | |
toLang = 'en' | |
salt = random.randint(32768, 65536) | |
sign = appid+q+str(salt)+secretKey | |
m1 = md5.new() | |
m1.update(sign) | |
sign = m1.hexdigest() | |
myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign | |
res = None | |
try: | |
httpClient = httplib.HTTPConnection('api.fanyi.baidu.com') | |
httpClient.request('GET', myurl) | |
#response是HTTPResponse对象 | |
response = httpClient.getresponse() | |
obj = json.loads(response.read().encode('utf-8')) | |
res = obj['trans_result'][0]['dst'] | |
except Exception, e: | |
print e | |
finally: | |
if httpClient: | |
httpClient.close() | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment