因为需要将命名实体中的组织机构名进一步区分为政府、企业、社会组织等,在easydl上做了一个文本分类模型,但是要用这个接口时候发现,
官方文档中竟然还在用urllib2的库,且不完整。好多地方会报错,坑太多,摸索了一会终于解决了,成功访问我的模型。
代码如下:
获取密钥
import urllib, urllib.request, sys import ssl # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=M3H6z5****&client_secret=z5O*****' request = urllib.request.Request(host) request.add_header('Content-Type', 'application/json; charset=UTF-8') response = urllib.request.urlopen(request) content = response.read() if (content): print(content)
获取结果
import urllib.request import json text="北大方正" request_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/text_cls/orgclassify" params = json.dumps({"text":text,"top_num": 6}).encode("utf-8") access_token = '24****’ request_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/text_cls/orgclassify?access_token=24******' request = urllib.request.Request(url=request_url, data=params) request.add_header('Content-Type', 'application/json') response = urllib.request.urlopen(request) content = response.read() if content: resu=eval(str(content,'utf-8')) print (resu['results'][0]['name'],resu['results'][0]['score']) print(resu['results'])