百度 api 使用

百度OCR 使用 但是上传图片一直失败 暂时不传
下面是翻译api的使用


# -*- coding: utf-8 -*-
import sys, urllib, urllib.request, json

url = 'http://apis.baidu.com/apistore/tranlateservice/translate?query=I+am+chinese%2C+and+you%3F&from=en&to=zh'


req = urllib.request.Request(url)

req.add_header("apikey", "换成自己的apikey")#肯定是数字和字母,当初自己在测试时,还没改,有中文,一直有编码问题,烦了好久,后来发现之后崩溃了....

resp = urllib.request.urlopen(req)
content = resp.read()

# print(type(content))

# aka = json.dump(content)
if(content):
    print('before: ',content) #b'{"errNum":0,"errMsg":"success","retData":{"from":"en","to":"zh","trans_result":[{"src":"I am chinese, and you?","dst":"\\u6211\\u662f\\u4e2d\\u56fd\\u4eba\\uff0c\\u4f60\\u5462\\uff1f"}]}}'
    content = content.decode() #byte to str
    print('after: ',content) #{"errNum":0,"errMsg":"success","retData":{"from":"en","to":"zh","trans_result":[{"src":"I am chinese, and you?","dst":"\u6211\u662f\u4e2d\u56fd\u4eba\uff0c\u4f60\u5462\uff1f"}]}}
    #一定要 json.loads()过后,\u6211\u662f\u4e2d\u56fd\u4eba\uff0c\u4f60\u5462\uff1f 才会转换成中文

    retData = json.loads(content)
    trans_result = retData['retData']['trans_result'][0]
    print(trans_result['dst'])

你可能感兴趣的:(百度 api 使用)