D:\ProgramData\Anaconda3\Lib\site-packages\pyhanlp\__init__.py 加入
WordVectorModel = LazyLoadingJClass('com.hankcs.hanlp.mining.word2vec.WordVectorModel')
# coding=utf-8
from flask import Flask
from flask import request
from flask import jsonify
from flask import make_response,Response
from flask_cors import CORS
from pyhanlp import *
port = 9999
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/')
def index():
str = "Hello, AI Server!"
print(str)
return str
# 成功请求
def successResp(data):
return jsonify(code=0, message="success", data=data)
# 错误请求
def errorResp(msg):
return jsonify(code=-1, message=msg)
# 分词服务
@app.route('/NLPWordSplit', methods=['POST'])
def NLPWordSplit():
Article = request.form.get('Article')
print(Article)
if Article == None or Article == "" :
rst = make_response(errorResp("请输入正确的数据!"))
rst.headers['Access-Control-Allow-Origin'] = '*'
return rst
word = ""
for term in HanLP.segment(Article):
curWord = str(term.word)
if len(curWord) != 0:
word = word + " " + curWord
print(word)
return getResult(word)
# 词向量服务
@app.route('/NLPWordNearest', methods=['POST'])
def NLPWordNearest():
Word = request.form.get('Word')
print(Word)
if Word == None or Word == "" :
rst = make_response(errorResp("请输入正确的数据!"))
rst.headers['Access-Control-Allow-Origin'] = '*'
return rst
try:
# WordVectorModel = LazyLoadingJClass('com.hankcs.hanlp.mining.word2vec.WordVectorModel')
# print(WordVectorModel)
# MODEL_FILE_NAME = r"E:\Model.txt"
# # 初始化模型
# word2vec = WordVectorModel(MODEL_FILE_NAME)
# print(word2vec)
if word2vec != None:
print("相关词分析")
word = word2vec.nearest(Word)
print(word)
data = ""
for x in word:
if data == "":
data = str(x).replace("=",":")
else:
data = data + "," + str(x).replace("=",":")
print(data)
word = "{" + data + "}"
# word = json.dumps(word)
# word = ','.join(word)
print(word)
return getResult(word)
else:
rst = make_response(errorResp("单词分析错误!"))
rst.headers['Access-Control-Allow-Origin'] = '*'
return rst
except Exception as e:
print("Exception:",e)
finally:
print("OK")
def getResult(word):
if word != "":
# 如果成功返回预测结果
rst = make_response(successResp(word))
rst.headers['Access-Control-Allow-Origin'] = '*'
return rst
else:
# 如果失败返回错误信息
rst = make_response(errorResp(word))
rst.headers['Access-Control-Allow-Origin'] = '*'
return rst
word2vec = None
if __name__ == '__main__':
# if not jpype.isThreadAttachedToJVM():
# jpype.attachThreadToJVM()
# WordVectorModel = jpype.JClass("com.hankcs.hanlp.mining.word2vec.WordVectorModel")
# print(WordVectorModel)
MODEL_FILE_NAME = r"E:\Model.txt"
# 初始化模型
word2vec = WordVectorModel(MODEL_FILE_NAME)
print("port:" + str(port))
app.run(debug = True,host = '0.0.0.0',port = port, threaded = True)
来源:oschina
链接:https://my.oschina.net/u/4417839/blog/3691052