LUIS 语义识别API调用方法

本例使用itchat获取微信文字消息,发送给LUIS返回识别消息,再将返回消息格式化后通过微信发回

关于itchat的使用参考我的另外一篇随笔itchat个人练习 语音与文本图灵测试例程

 1 # -*- coding: UTF-8 -*-
 2 import requests
 3 import itchat
 4 import json
 5 
 6 def get_response(msg):
 7     headers = {
 8         # Request headers
 9         'Ocp-Apim-Subscription-Key': '=====填上自己的LUIS API密钥========',
10     }
11 
12     params ={
13         # Query parameter
14         'q': msg,#需要检测的消息
15         # Optional request parameters, set to default values
16         'timezoneOffset': '0',
17         'verbose': 'false',
18         'spellCheck': 'false',
19         'staging': 'false',
20     }
21 
22     try:
23         r = requests.get('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/'+'=====填上自己的luisAppId=====',headers=headers, params=params)
24         print (r.json())
25         return json.dumps(r.json())#json()是取出json消息,dumps()是把json对象转换为字符串才能返回
26 
27     except Exception as e:
28         print("[Errno {0}] {1}".format(e.errno, e.strerror))
29 
30 def changeEntity(entitiesList):
31     #用于把返回的entities取出来放在list里
32     entityList=[]
33     for item in entitiesList:
34         entityList.append(item.get('entity'))
35     return entityList
36 
37 # 这里是我们在“1. 实现微信消息的获取”中已经用到过的同样的注册方法
38 @itchat.msg_register(itchat.content.TEXT)
39 def tuling_reply(msg):
40     # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
41     defaultReply = 'I received: ' + msg['Text']
42     # 如果图灵Key出现问题,那么reply将会是None
43     jsonReply = json.loads(get_response(msg['Text']))
44     # 返回json数据格式
45     # {
46     #     'query': <str> , 
47     #     'topScoringIntent': {
48     #         'intent': <str> , 
49     #         'score': <float>}, 
50     #         'entities': <list>
51     # }
52     reply = "提问:" + jsonReply.get('query') + 
53             "\n意图:" + jsonReply.get('topScoringIntent').get('intent') + 
54             "\n分数:" + repr(jsonReply.get('topScoringIntent').get('score')) + 
55             "\n实体:" + repr(changeEntity(jsonReply.get('entities')))
56     # a or b的意思是,如果a有内容,那么返回a,否则返回b
57     # 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试
58     return reply or defaultReply
59 
60 # 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动hotReload=True
61 itchat.auto_login(hotReload=True)
62 itchat.run()
posted @ 2018-10-18 14:58  evtricks  阅读(612)  评论(0编辑  收藏  举报