基于python的语言检测服务

1.  Python环境安装【目前使用版本为:python2.7.5】

2.  安装服务启动需要模块

yum install python-pip  :如果无法直接通过下载安装,请移步至官方下载: https://pypi.python.org/pypi/pip/;下载时使用版本pip-8.1.0.tar.gz

  如果下载本地环境的话,需要上传至服务器:

tar -zxvf pip-8.1.0.tar.gz
cd pip-8.1.0
python setup.py install

  安装成功如下图:

      

3. 安装依赖环境:

  • pip install flask

    安装成功效果如下图:

    

    注:如果出现上图中的黄色提示信息,请按提供进行pip版本的升级,执行命令:pip install --upgrade pip

  • pip install validictory

    安装成功效果图:

    

pip install logging

   安装成功效果图:

    

  • pip install langid

    安装效果图:

        

4. 启动服务:nohup python Language_Detection.py &

   服务具体代码如下:

# coding=utf8
'''
Created on 2015年4月17日

@author: Jack 杰之蓝
'''
import langid
from flask import Flask, request, abort, Response
import logging
import json
import validictory


class Language_detection:
    def __init__(self,logger):
        self.logger = logger
    def post(self):
        if not request.json:
            abort(400)
        self.logger.info('Received new task [POST]')
        self.logger.info(request.json)
        result = self._dispatch_task(request.json)
        return self._wrap_result(result)
    def get(self):
        args = request.args.to_dict()
        self.logger.info(args)
        result = self._dispatch_task(args)
        self.logger.info('Received new task [GET]')
        return self._wrap_result(result)
    def _dispatch_task(self,task):
        result = {}
        try:
            self._validate(task)
        except ValueError as e:
            return {"errorCode":1, "errorMessage": str(e)}
        
        try:
            result['result'] = langid.classify(task['text'])[0]
        except ValueError as e:
            return {"errorCode":2, "errorMessage": str(e)}
        
        result['errorCode'] = 0
        result['errorMessage'] = 'Succeed'
        return result
    def _wrap_result(self,result):
        dump = json.dumps(result, encoding = 'utf-8', ensure_ascii=False, indent=4)
        callback = request.args.get('jsoncallback')
        if callback:
            return '%s(%s)' % (callback, dump)
        else:
            return Response(json.dumps(result, encoding='utf-8', ensure_ascii=False, indent=4), mimetype='application/javascript')
    def _validate(self,task):
        schema = {
                  'type': 'object',
                  'properties': {
                                 'text': {'type': "string"}
                                 },
                  }
        validictory.validate(task,schema)
    
def main():
    app = Flask(__name__)
    logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(message)s")
    logger = logging.getLogger('Language detection')
    detection = Language_detection(logger)
    app.route('/detection', methods = ['POST'])(detection.post)
    app.route('/detection')(detection.get)
    app.run(host = '', port = 9006, threaded = True)
if __name__ == "__main__":
    main()
    
View Code

5. 服务调用:

http://172.16.4.200:9006/detection?text=你好,杰之蓝

调用结果:

{
    "errorCode": 0, 
    "errorMessage": "Succeed", 
    "result": "zh"
}
原文地址:https://www.cnblogs.com/whyloverjack/p/5480847.html