6月12日

做机器人问答,给的案例非常有意思,不是通过java的前后端实现,而是基于python的flask来实现前后台,这对我来说十分新奇,我看到他是通过ip 和端口号将后端和前台页面进行通信。他的前台也写的非常夸张,一万多条js,所有页面的实现都在js里面。这是我的后端代码,来实现对问题的回答

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', 'root'))
        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查询语句
        # shift+tab 后退制表符

        query_str = "match (s)-[r2:`法规属于`]->(e) where  s.name='" + ques + "' return e.name"
        print(query_str)
        law=''
        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']
                    law=ans_str
                    print(ans_str)
                    # 如果结果里面没有才加入
                    if ans_str not in ansList:
                        ansList.append(ans_str)
        print(ansList)
        query_str1 = "MATCH (p)-[r:`法规属于`]->(s) where  s.name='" + law + "' RETURN p.name LIMIT 2"
        print(query_str1)
        case=[]
        if (len(query_str1) > 0):
            answer = qa_graph.run(query_str1).data()
            print(answer)
            if answer:
                for item in answer:
                    print(item)
                    case.append(item['p.name'])
        re_ans = "您问的内容属于:\n"

        for i in range(len(ansList)):
            re_ans += "(%s) %s \n" % (i + 1, ansList[i])
        print(re_ans)
        re_ans=re_ans+"\n";
        re_ans+="该法案相关案例:"
        for j in range(len(case)):
            re_ans += "%s. %s ;" % (j + 1, case[j])
        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)

 

posted @ 2022-06-12 22:10  不咬牙  阅读(7)  评论(0编辑  收藏  举报