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"))

 由于百度翻译不提供音标、发音之类的内容很是不方便,在百度翻译页面上发现数据来自金山词霸,于是乎用金山词霸看看

 

 1 #/usr/bin/env python3
 2 #coding=utf8
 3  
 4 “”“金山词霸版”“”
 5 
 6 import http.client
 7 import hashlib
 8 import urllib
 9 import random
10 import json
11 
12 def getTransResult(q,type = "json"): 
13 
14 
15     
16     httpClient = None
17     myurl = '/api/trans/vip/translate'
18     #q = 'hello baidu trans'    #要翻译的内容
19     myurl = "/api/dictionary.php?w="+q+"&type="+type+"&key=xxxxxxxxxxxx"  #开发者Key
20     
21     try:
22         httpClient = http.client.HTTPConnection('dict-co.iciba.com')
23         httpClient.request('GET', myurl)
24         #response是HTTPResponse对象
25         response = httpClient.getresponse()     #获取返回结果
26         mresult = json.loads(response.read().decode("utf-8"))
27         
28         
29         #print(mresult)
30         return mresult
31     
32     except Exception as e:
33         print(e)
34     finally:
35         if httpClient:
36             httpClient.close()
37             
38 
39 if __name__ == "__main__":
40     print(getTransResult("hello"))
41     

要啥有啥感觉棒棒哒