民法典自动问答平台
今天做了民法典自动问答平台的实验
成果:
代码:import json
from flask import Flask, request
from py2neo import Graph
from pyhanlp import *
app = Flask(__name__)
@app.route("/qa", methods=['POST', 'GET'])
def kg_qa():
if request.method == 'GET':
ques = request.args.get('question')
cb = request.args.get('callback')
print(ques)
qa_graph = Graph('http://localhost:7474', password='123456')
keyword = []
ansList = []
# CRF 词法分析器
CRFLexicalAnalyzer = JClass("com.hankcs.hanlp.model.crf.CRFLexicalAnalyzer")
analyzer = CRFLexicalAnalyzer()
han_word_pos = analyzer.analyze(ques).toString()
print(han_word_pos)
wordlist = han_word_pos.split(" ")
for word in wordlist:
pos = word.split("/")
if "n" in pos[1]:
print(pos[0],pos[1])
if pos[0] not in keyword:
keyword.append(pos[0])
print(keyword)
query_str = ""
#枚举组成cypher查询语句
for key1 in keyword:
for key2 in keyword:
query_str = "match (s)-[r2:`法规属于`]->(e) where s.name=~'.*" + key1 + ".*' return e.name limit 1"
print(query_str)
if(len(query_str) > 0):
answer = qa_graph.run(query_str).data()
print(answer)
if answer:
for item in answer:
print(item)
ans_str = item['e.name']
print(ans_str)
#如果结果里面没有才加入
if ans_str not in ansList:
ansList.append(ans_str)
print(ansList)
re_ans = "您想问的是不是这些问题:\n"
for i in range(len(ansList)):
re_ans += "(%s) %s \n"%(i+1,ansList[i])
print(re_ans)
result = {
"question" : ques,
"answer" : re_ans
}
res_str = json.dumps(result)
cb_str = cb + "(" + res_str + ")"
print(cb_str)
return cb_str
return 'Error Format'
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('127.0.0.1', 9001, app)
前端代码;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="author" content="">
<meta name="description" content=""/>
<meta name="format-detection" content="telephone=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="white" />
<title>chatbot</title>
<style type="text/css">
body{ margin: 0; font-size: 18px; background-color: #fff;}
</style>
</head>
<body>
<h1>欢迎大家参加本期知识图谱学习</h1>
<div>
讲师:蔡丰龙<br>
</div>
<script type="text/javascript" src="robot/robot.js?022107"></script>
</body>
</html>
后台数据库: