Beginning to learn Python, I want to try to write a few small programs. Accidentally found that the Baidu Translate Open Platform provides an API that can provide us with high-quality translation services. This is the first applet I wrote in Python, and this article is also my first blog, so I'm excited to think about it. Now let's introduce the method of writing online translation program by calling Baidu Translate API.
Now Baidu Translate Open Platform provides free translation services of 2 million characters per month. As long as you have a Baidu account and apply to become a developer, you can get the required account and password. Here is the developer application link:
http://api.fanyi.baidu.com/api/trans/product/index
For the convenience of use, Baidu Translate Open Platform provides detailed access documents, the links are as follows:
http://api.fanyi.baidu.com/api/trans/product/apidoc
Program demo:
The detailed usage method is listed in the translation document. The following is the original text of the access document:
Example: Translate apple from English to Chinese:
q=apple
from=en
to=zh
appid=2015063000000001
salt=1435660288
Platform Assigned Key: 12345678
Generate sign:
>concatenated string 1
Splicing appid=2015063000000001 + q=apple + salt=1435660288 + key=12345678
get string 1 = 2015063000000001 apple 1435660288 12345678
>Calculate signature sign (encrypt string 1 with md5, note that string 1 must be UTF-8 encoded before calculating md5)
sign=md5(2015063000000001apple143566028812345678)
sign=f89f9594663708c1605f3d736d01d2d4
The full request is:
Generation of signature
Signature calculation can be achieved through hashlib.md5() in the hashlib module provided by Python
Take the string in the access document as an example:
import hashlib m = '2015063000000001apple143566028812345678' m_MD5 = hashlib.md5(m) sign = m_MD5.hexdigest() print 'm = ',m print 'sign = ',sign
After the signature is obtained, a URL request is generated according to the requirements in the access document, and the translation result can be returned after submission. The following is a screenshot of the fields provided by the access document and their corresponding descriptions:
Parse the return result
The return value after submitting the URL is in json format, and the result can be parsed using the json module:
{"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"\u82f9\u679c"}]}
import json result = '{"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"\u82f9\u679c"}]}' data = json.loads(result) print data['trans_result'][0]['dst']
至此,我们完成了有关API调用的所有关键步骤。
以下为全部代码:
# -*- coding: utf-8 -*- import urllib2 import hashlib import json import random class Baidu_Translation: def __init__(self): self._q = '' self._from = '' self._to = '' self._appid = 0 self._key = '' self._salt = 0 self._sign = '' self._dst = '' self._enable = True def GetResult(self): self._q.encode('utf8') m = str(Trans._appid)+Trans._q+str(Trans._salt)+Trans._key m_MD5 = hashlib.md5(m) Trans._sign = m_MD5.hexdigest() Url_1 = 'http://api.fanyi.baidu.com/api/trans/vip/translate?' Url_2 = 'q='+self._q+'&from='+self._from+'&to='+self._to+'&appid='+str(Trans._appid)+'&salt='+str(Trans._salt)+'&sign='+self._sign Url = Url_1+Url_2 PostUrl = Url.decode() TransRequest = urllib2.Request(PostUrl) TransResponse = urllib2.urlopen(TransRequest) TransResult = TransResponse.read() data = json.loads(TransResult) if 'error_code' in data: print 'Crash' print 'error:',data['error_code'] return data['error_msg'] else: self._dst = data['trans_result'][0]['dst'] return self._dst def ShowResult(self,result): print result def Welcome(self): self._q = 'Welcome to use icedaisy online translation tool' self._from = 'auto' self._to = 'zh' self._appid = 201609240000***** self._key = '******' self._salt = random.randint(10001,99999) welcome = self.GetResult() self.ShowResult(welcome) def StartTrans(self): while self._enable: self._q = raw_input() if cmp(self._q, '!quit') == 0: self._enable = False print 'Thanks for using!' break _q_len = len(self._q) if _q_len < 4096: result = self.GetResult() self.ShowResult(result) else: print 'Exceeds the maximum limit of 4096 characters' #----------- 程序的入口 ----------- print u""" --------------------------------------- 程序:icedaisy的在线翻译工具 版本:0.2 作者:icedaisy 日期:2016-09-25 语言:Python 2.7 功能:输入原文后得到翻译结果 原理:调用百度翻译API 退出:输入!quit --------------------------------------- """ Trans = Baidu_Translation() Trans.Welcome() Trans.StartTrans()