标签:
1 #/usr/bin/env python3 2 #coding=utf8 3 4 """百度翻译api功能实现函数,本模块基于Python3.x实现,getTransResult(q)中参数q是需被翻译的内容,目前该函数的源语言默认英文,目标语言默认简体中文""" 5 6 7 import http.client 8 import hashlib 9 import urllib 10 import random 11 import demjson 12 13 def getTransResult(q): 14 15 """ 16 从百度翻译API获取源语言翻译结果的实现函数。get请求字符串构造具体请参照百度翻译开发者文档 17 fromLang&&toLang分别是源语言与目标语言,现阶段默认为英语与简体中文,后期可根据需求作为函数参数动态传入 18 """ 19 20 appid = ‘xxxxxxxxxxxx‘ #开发者id 21 secretKey = ‘xxxxxxxxxx‘ #开发者密钥 22 23 24 httpClient = None 25 myurl = ‘/api/trans/vip/translate‘ 26 #q = ‘hello baidu trans‘ #要翻译的内容 27 fromLang = ‘en‘ #源语言 28 toLang = ‘zh‘ #目标语言 29 salt = random.randint(32768, 65536) #随机数 30 31 sign = appid+q+str(salt)+secretKey #需要生成md5码的字符串 32 33 m1 = hashlib.md5(sign.encode(encoding=‘utf-8‘)) 34 sign = m1.hexdigest() 35 myurl = myurl+‘?appid=‘+appid+‘&q=‘+urllib.parse.quote(q)+‘&from=‘+fromLang+‘&to=‘+toLang+‘&salt=‘+str(salt)+‘&sign=‘+sign #get请求字符串 36 37 try: 38 httpClient = http.client.HTTPConnection(‘api.fanyi.baidu.com‘) 39 httpClient.request(‘GET‘, myurl) 40 #response是HTTPResponse对象 41 response = httpClient.getresponse() #获取返回结果 42 mresult = demjson.decode(response.read()) #json解码 43 #print(mresult["trans_result"][0]["dst"]) 44 return mresult["trans_result"][0]["dst"] 45 46 except Exception as e: 47 print(e) 48 finally: 49 if httpClient: 50 httpClient.close() 51 52 53 if __name__ == "__main__": 54 print(getTransResult("hello"))
标签:
原文地址:http://www.cnblogs.com/vawter/p/5928720.html