医疗问答系统详解二

医疗问答系统介绍:博客

这部分是学习如何获得意图后查询知识图谱中的相关回答

知识图谱中进行答案的查询

在知识图谱中进行问题答案的查询所用到的主体类 AnswerSearching框架:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class AnswerSearching:
def __init__(self):
pass

## 根据不同的实体和意图构造cypher查询语句
def question_parser(self, data):
pass

## 将问题转变为cypher语句
def transfer_to_sql(self, label, entities, intent):
pass

## 执行cypher查询语句,返回结果
def searching(self, sqls):
pass

## 根据不同的意图返回不同模板的答案
def answer_template(self, intent, answers):
pass

根据不同的实体和意图构造cypher查询语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def question_parser(self, data):
sqls = []

if data:
for intent in data["intentions"]:
sql_ = {}
sql_["intention"] = intent

sql = []
## 我觉得这里全部应该为 if 语句,而且 sql赋值应该改为append。
if data.get("Disease"):
sql = transfer_to_sql("Disease", data["Disease"], intent)
elif data.get("Alias"):
sql = transfor_to_sql("Alias", data["Alias"], intent)
elif data.get("Symptom"):
sql = transfor_to_sql("Symptom", data["Symptom"], intent)
elif data.get("Complication"):
sql = transfor_to_sql("Complication", data["Complication"], intent)

if sql:
sql_['sql'] = sql
sqls.append(sql_)
return sqls

将问题转变为cypher查询语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def transfor_to_sql(self, label, entities, intent):
"""
:param label:实体标签
:param entities:实体列表
:param intent:查询意图
:return:cypher查询语句
"""
if not entities:
return []
sql = []

# 查询症状
if intent == "query_symptom" and label == "Disease":
sql = ["MATCH (d:Disease)-[:HAS_SYMPTOM]->(s) WHERE d.name='{0}' RETURN d.name,s.name".format(e)
for e in entities]
# 查询治疗方法
if intent == "query_cureway" and label == "Disease":
sql = ["MATCH (d:Disease)-[:HAS_DRUG]->(n) WHERE d.name='{0}' return d.name,d.treatment," \
"n.name".format(e) for e in entities]
# 查询治疗周期
if intent == "query_period" and label == "Disease":
sql = ["MATCH (d:Disease) WHERE d.name='{0}' return d.name,d.period".format(e) for e in entities

### ... (下面类似)

执行cypher查询,返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def searching(self, sqls):
final_answers = []

for sql_ in sqls:
intent = sql_['intent']
queries = sql_['sql']
answers = []
for query in queries:
ress = graph.run(quary).data()
answers += ress
final_answer = self.answer_template(intent, answers)
if final_answer:
final_answers.append(final_answer)
return final_answers

根据不同意图,返回不同模板的答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def answer_template(self, intent, answers):
final_answer = ""

if not answers:
reutrn ""

if intent == "query_symptom":
disease_dic = {}
for data in answers:
d = data['d.name']
s = data['s.name']
if d not in disease_dic:
disease_dic[d] = [s]
else:
disease_dic[d].append(s)
i = 0
for k, v in disease_dic.items():
if i >= 10:
break
final_answer += "疾病 {0} 的症状有 {1} \n".format(k, ','.join(list(set(v))))
i += 1

### ... 其余类似

以上便是得到并返回知识图谱中的答案的过程。

参考链接:链接