[NodeJS]NodeJS+Python 3を使用した形態学ブラウザ

2913 ワード

[NodeJS]NodeJS+Python 3を使用した形態学ブラウザ


準備物

  • Python 3(エンジン、KonLPy、MeCab)
  • java
  • nodejs(エンジン、express、python-shell、cors)
  • 参考資料


    KonLPy取付:http://konlpy.org/ko/v0.4.4/install/ MeCab類用法:http://konlpy.org/ko/v0.4.4/api/konlpy.tag/#mecab-class

    mecab.py

    # -*- coding: utf-8 -*- 
    """
    1. sudo apt-get install curl
    2. bash <(curl -s https://raw.githubusercontent.com/konlpy/konlpy/master/scripts/mecab.sh)
    3. http://searchtool.tistory.com/3
    
    curl -L https://bitbucket.org/eunjeon/mecab-ko-dic/downloads/mecab-ko-dic-2.0.1-20150920.tar.gz | tar -xz
    cd mecab-ko-dic-2.0.1-20150920
    ./autogen.sh
    ./configure
    make
    make install
    mecab -d /usr/local/lib/mecab/dic/mecab-ko-dic
    
    # 설치 및 가동 확인 후 사용자 사전 추가 후 재설치
    vi ./user-dic/nnp.csv
    ./tools/add-userdic.sh
    make install
    mecab -d /usr/local/lib/mecab/dic/mecab-ko-dic
    
    """
    import sys
    from konlpy.tag import Mecab
    mecab = Mecab()
    
    total = len(sys.argv)
    cmdargs = str(sys.argv)
    cm = str(sys.argv[1])
    
    
    ret = mecab.pos(u''+cm)
    print(ret)

    app.js

    var app = require('express')();
    var http = require('http').Server(app);
    var url = require('url');
    var PythonShell = require('python-shell');
    var colors = require('colors');
    
    
    if(!String.prototype.trim) {
      String.prototype.trim = function () {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
      };
    }
    
    // 전체 치환
    if(!String.prototype.replaceAll) {
        String.prototype.replaceAll = function(org, dest) {
            return this.split(org).join(dest);
        }
    }
    
    
    app.get('/', function(req, res){
        res.send('주소/data/?k=한글문장을 입력');
    
    });
    app.get('/data', function(req, res, next){
    
        res.set('Content-Type', 'text/plain');
        var url_parts = url.parse(req.url, true);
        var query = url_parts.query;
        if(query['k'] != undefined) {
            var options = {
              mode: 'text',
              pythonPath: 'python3',
              scriptPath: '',
              args: [query['k']]
            };
            PythonShell.run('mecab.py', options, function (err, results) {
                if(err) throw err;
    
                var data = String(results);
                data = data.replace(/\('(.*?)',\s'(.*?)'\)/g, '{"value":"$1", "type":"$2"}');
                res.send(data);
            });
        }
    });
    
    http.listen(7777, function(){
        console.log('konlpy server is ready!!'.rainbow);
    });

    TEST

    테스트: 주소/data/?k=한글문장을 입력