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

时间:2023-03-10 04:16:52
百度翻译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

 #!/usr/bin/env python3
#coding=utf8
import http.client
import hashlib
import urllib
import urllib.request
import random
import re def chinese_handle():
#连接百度翻译web服务器
httpclient = http.client.HTTPConnection('api.fanyi.baidu.com')
#要提交的请求
myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
#输入要查询的单词
'''
array = []
user_input = input('please enter needed translate word:')
while user_input != '0':
array.append(user_input)
user_input = input('please enter needed translate word:')
str2 = ""
for c in array:
str2 = str2 + c +'\n';
query = str2
'''
query = input('please enter the word:')
#输入语言
fromlang = 'en'
#输出语言
tolang = 'zh'
#申请的百度appid
appid = ''
#申请的密钥
secretKey = 'osubCEzlGjzvw8qdQc41'
#随机分配一个数
salt = random.randint(32768,65536)
#拼接得到字符串
str1 = appid+query+str(salt)+secretKey
str1 = str1.encode('utf-8')
#对字符串str1进行md5加密
m = hashlib.md5()
m.update(str1)
#生成签名sign
sign = m.hexdigest()
#拼接成完整请求
myurl = myurl+'?appid='+appid+'&q='+urllib.request.quote(query)+'&from='+fromlang+'&to='+tolang+'&salt='+str(salt)+'&sign='+sign
try:
#发送请求
httpclient.request('GET',myurl)
response = httpclient.getresponse()
content = response.read()
#编码为utf-8可以解字节操作,将bytes转化为str
content = content.decode('utf-8')
#提取其中的结果
mstr = r'\\.....\\.....'
mobj = re.search(mstr,content)
#先编码为gbk再解码unicode即可显示汉字
obj = mobj.group().encode('gbk')
obj = obj.decode('unicode-escape')
print('翻译结果:',obj)
except Exception:
print('error...')
finally:
if httpclient:
httpclient.close() if __name__ == '__main__':
while 1:
chinese_handle()

下面是运行结果:

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

出现的bug:

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