1. First to register Baidu API to become a developer,
Here is a link to the developer application:
Http://api.fanyi.baidu.com/api/trans/product/index
For ease of use, Baidu Translation open platform provides detailed access documentation, links are as follows:
Http://api.fanyi.baidu.com/api/trans/product/apidoc
Detailed usage is listed in the translated document, and the following is the original text of the access document:
Example: Translating Apple from English to Chinese:
Request Parameters:
Q=apple
from=en
To=zh
appid=2015063000000001
salt=1435660288
Platform-assigned key: 12345678
Generate sign:
> Stitching Strings 1
Stitching appid=2015063000000001+q=apple+salt=1435660288+ key =12345678
Get string 1 =2015063000000001Apple143566028812345678
> Calculate signature sign (do MD5 encryption on string 1, note that string 1 must be UTF-8 encoded before MD5 is calculated)
SIGN=MD5 (2015063000000001apple143566028812345678)
Sign=f89f9594663708c1605f3d736d01d2d4
The complete request is:
http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001 &salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
Generation of signed Sign
Signature calculation can be achieved by 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
Once the signature is received, the URL request is generated as requested in the access documentation , and the translation results are returned after submission. The following are the fields provided by the access documentation and the corresponding descriptions:
{"from": "en", "to": "zh", "trans_result": [{"src": "Apple", "DST": "\u82f9\u679c"}]}
Parse return result
The return value after the URL is submitted is in JSON format, which can be parsed using the JSON module:
- Import JSON
- result = ' {' from ': ' en ', ' to ': ' zh ', ' trans_result ': [{' src ': ' apple ', ' DST ': ' \u82f9\u679c '}]} '
- data = Json.loads (Result)
- Print data['trans_result ' [0][' DST ']
These are all programs called by the API.
Using Python to implement Baidu API calls