基于金融知识图谱的问答机器人
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",auth=("neo4j","12345678"),name="neo4j")
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:
if('董事' in key2):
query_str = "match (e)-[r2:`董事会成员`]->(s) where s.name='%s' return e.name"%(key1)
if('概念' in key2):
query_str = "match (s)-[r2:`概念属于`]->(e) where s.name='%s' return e.name"%(key1)
if('行业' in key2):
query_str = "match (s)-[r2:`行业属于`]->(e) where s.name='%s' return e.name"%(key1)
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>