Skip to content

Instantly share code, notes, and snippets.

@zweite
Last active April 2, 2018 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zweite/15504929e7506c5c14dff9269a5b7b28 to your computer and use it in GitHub Desktop.
Save zweite/15504929e7506c5c14dff9269a5b7b28 to your computer and use it in GitHub Desktop.
#! /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