如何判斷一句話是否通順,通順程度如何,這裏用到了百度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}’
結果ppl爲:69.303,表明已經很好了,但是如果人去讀這句話,還是有點彆扭的。
這個接口對精細度要求不高的可以使用。