百度翻译api初使用(很久没写python了,写几行玩玩)

调用free api做做简易的翻译

这个是百度翻译api文档

http://api.fanyi.baidu.com/api/trans/product/apidoc

照着百度api给的文档向web服务器发送GET/POST请求,得到需要的翻译json格式,再进行解析即可。

但是貌似只能单词翻译,而且还会出现无法翻译“me”或者“he”的bug,果然百度翻译靠不住

下面上源码,一开始可以在官网上下载demo看看:

配置环境:python 3.x 即可

en_to_zh.py   

 1 #!/usr/bin/env python3
 2 #coding=utf8
 3 import http.client
 4 import hashlib
 5 import urllib
 6 import urllib.request
 7 import random
 8 import re
 9     
10     
11 
12 def chinese_handle():
13 #连接百度翻译web服务器
14     httpclient = http.client.HTTPConnection('api.fanyi.baidu.com')
15     #要提交的请求
16     myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
17     #输入要查询的单词
18     '''
19     array = []
20     user_input = input('please enter needed translate word:')
21     while user_input != '0':
22         array.append(user_input)
23         user_input = input('please enter needed translate word:')
24     str2 = ""
25     for c in array:
26         str2 = str2 + c +'
';
27     query = str2
28     '''
29     query = input('please enter the word:')
30     #输入语言
31     fromlang = 'en'
32     #输出语言
33     tolang = 'zh'
34     #申请的百度appid
35     appid = '20151113000005349'
36     #申请的密钥
37     secretKey = 'osubCEzlGjzvw8qdQc41'
38     #随机分配一个数
39     salt = random.randint(32768,65536)
40     #拼接得到字符串
41     str1 = appid+query+str(salt)+secretKey
42     str1 = str1.encode('utf-8')
43     #对字符串str1进行md5加密
44     m = hashlib.md5()
45     m.update(str1)
46     #生成签名sign
47     sign = m.hexdigest()
48     #拼接成完整请求
49     myurl = myurl+'?appid='+appid+'&q='+urllib.request.quote(query)+'&from='+fromlang+'&to='+tolang+'&salt='+str(salt)+'&sign='+sign
50     try:
51         #发送请求
52         httpclient.request('GET',myurl)
53         response = httpclient.getresponse()
54         content = response.read()
55         #编码为utf-8可以解字节操作,将bytes转化为str
56         content = content.decode('utf-8')
57         #提取其中的结果
58         mstr = r'\.....\.....'
59         mobj = re.search(mstr,content)
60         #先编码为gbk再解码unicode即可显示汉字
61         obj = mobj.group().encode('gbk')
62         obj = obj.decode('unicode-escape')
63         print('翻译结果:',obj)
64     except Exception:
65         print('error...')
66     finally:
67         if httpclient:
68             httpclient.close()
69             
70             
71 if __name__ == '__main__':
72     while 1:
73         chinese_handle()

下面是运行结果:

出现的bug:

原文地址:https://www.cnblogs.com/jeavenwong/p/8268741.html