利用百度AI接口评估语句通顺度

如何判断一句话是否通顺,通顺程度如何,这里用到了百度AI的DNN语言模型接口

例如:“今天成立了*”,对此句子分析

1、获取百度的token

client_id:是主持百度AI后的id
client_secret:相当于秘钥
获取token可以访问:https://jingyan.baidu.com/article/1612d50088bab6e20e1eee87.html

# 获取百度AI的access_token
url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=******&client_secret=******'
res = eval(requests.get(url).text)
assess_token = res['access_token']
print(assess_token)

2、访问接口

def get_value(text):
    '''
    请求百度AI DNN语言模型,判断语句的通顺度
    '''
    assess_token = '24.21c5c0b1e62afccec4c444614fc8ea9f.2592000.1546754443.282335-15082009'
    url = 'https://aip.baidubce.com/rpc/2.0/nlp/v2/dnnlm_cn?access_token=' + str(assess_token)
    data = {"text":text}
    data=json.dumps(data).encode('GBK')
    request = urllib.request.Request(url, data)
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request).read()
    result = str(response, encoding="gbk")
    # 可以自定义想要的结果
#     filter_str = re.compile('ppl": (.*)')
#     value = re.findall(filter_str,str(response))
#     return float(str(value)[2:-4])
    return result
print(get_value(‘今天成立了*’))

帮助文档参考:https://ai.baidu.com/docs#/NLP-API/0153c13e
结果为:

‘{“log_id”: 8547559822052314773, “text”: “今天成立了*”, “items”: [{“word”: “今天”, “prob”: 0.00124328}, {“word”: “成立”, “prob”: 3.91631e-05}, {“word”: “了”, “prob”: 0.164486}, {“word”: “中华”, “prob”: 0.000286813}, {“word”: “人民”, “prob”: 0.0594741}, {“word”: “共和”, “prob”: 0.968625}, {“word”: “国”, “prob”: 0.984193}], “ppl”: 69.303}’
利用百度AI接口评估语句通顺度

结果ppl为:69.303,表明已经很好了,但是如果人去读这句话,还是有点别扭的。
这个接口对精细度要求不高的可以使用。