百度翻译API pyhon demo

2021-02-12 19:19

阅读:544

# -*- coding:utf-8 -*-

from http.client import HTTPConnection
import hashlib
import urllib
import random

appid = ‘20151113000005349‘
secretKey = ‘osubCEzlGjzvw8qdQc41‘


httpClient = None
myurl = ‘/api/trans/vip/translate‘
q = ‘apple‘
fromLang = ‘en‘
toLang = ‘zh‘
salt = random.randint(32768, 65536)

sign = appid+q+str(salt)+secretKey
# m1 = md5.new()
m1 = hashlib.md5()
m1.update(sign.encode())
sign = m1.hexdigest()
myurl = myurl+‘?appid=‘+appid+‘&q=‘+urllib.parse.quote(q)+‘&from=‘+fromLang+‘&to=‘+toLang+‘&salt=‘+str(salt)+‘&sign=‘+sign

try:
httpClient = HTTPConnection(‘api.fanyi.baidu.com‘)
httpClient.request(‘GET‘, myurl)

#response是HTTPResponse对象
response = httpClient.getresponse()
print (response.read())
except Exception as e:
print (e)

finally:
if httpClient:
httpClient.close()


评论


亲,登录后才可以留言!