バイドゥNLP語類似度インタフェースDemo



def similirity(word1,word2):
    token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
    # 1.  token
    api_key='hGs3TEt3sN3XcI3VyIAyuTQp'
    api_secert='P7tCqnwMBEPs6bpEa4TOr4voTtAtTdxQ'

    token_url = token_url % (api_key, api_secert)

    r_str = urllib.request.urlopen(token_url).read()
    r_str = str(r_str, encoding="utf-8")
    token_data = json.loads(r_str)
    token_str = token_data['access_token']

    url_all='https://aip.baidubce.com/rpc/2.0/nlp/v2/word_emb_sim?access_token='+str(token_str)

    data2={'word_1': word1, 'word_2': word2}
    post_data = json.dumps(data2)
    header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko','Content-Type':'application/json'}
    req = urllib.request.Request(url=url_all, data=bytes(post_data,encoding="gbk"),headers=header_dict)
    res = urllib.request.urlopen(req).read()
    # print(res)
    r_data= str(res, encoding="GBK")
    # print(r_data)
    res=json.loads(r_data)
    print([word1,word2,res['score']])