TIP게시판

제목 형태소 검색기
글쓴이 테러보이 작성시각 2017/03/29 09:25:49
댓글 : 7 추천 : 0 스크랩 : 0 조회수 : 15828   RSS
테러보이

준비물

python3 (엔진, KoNLPy, MeCab)

java

nodejs (엔진, express, python-shell, colors)

 

참조자료

KoNLPy 설치법: http://konlpy.org/ko/v0.4.4/install/

MeCab class 사용법: 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)

# py.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){
	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;

			//console.log('results: %j', results);
			var data = String(results);
			//data.replace("('", '{"');
			data = data.replaceAll("('", '{"value":"');
			data = data.replaceAll("', '", '", "type":"');
			data = data.replaceAll("')", '"}');
			res.send(data);
		});
	}
});

http.listen(7777, function(){

	/*
	console.log('color test: bold'.bold);
	console.log('color test: italic'.italic);
	console.log('color test: underline'.underline);
	console.log('color test: inverse'.inverse);
	console.log('color test: yellow'.yellow);
	console.log('color test: cyan'.cyan);
	console.log('color test: white'.white);
	console.log('color test: magenta'.magenta);
	console.log('color test: green'.green);
	console.log('color test: red'.red);
	console.log('color test: grey'.grey);
	console.log('color test: blue'.blue);
	console.log('color test: rainbow'.rainbow);
	console.log('color test: zebra'.zebra);
	console.log('color test: random'.random);
	*/
	console.log('konlpy server is ready!!'.rainbow);
});

/*
// 형태소 검색

*/

 

 다음글 curl 2차원 배열 전송 (3)
 이전글 액티브레코드에 IF문 사용하기 [부제. mysql bo... (2)

댓글

테러보이 / 2017/03/29 09:26:14 / 추천 0
정규식에 약해서 nodejs측은 개판입니다 ㅠ.ㅠ
한대승(불의회상) / 2017/03/29 10:18:22 / 추천 0
와우~
테러보이 / 2017/03/29 10:46:48 / 추천 0

py.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);
});

 

변종원(웅파) / 2017/03/29 12:30:22 / 추천 0
mecab은 좀 관심이 갔었는데 파이썬이라.. (전 아직 10년도 넘은 php로 된 형태소분석기 사용하고 있습니다. ㅎㅎ)
테러보이 / 2017/03/29 14:07:58 / 추천 0
@웅파 몇년전에 봤던 자료인데 mecab설치 후 사용가능한 php패키지가 있었던걸로 알고있습니다. 저같은 경우는 패키지 설치 없이 쓰기위해 cutl로 끌어다가 쓰는걸 가만 한거죠 ㅎㅎ

개인적으로 하나의 언어에 종속되기보다는 특성에맞는 효율적은 언어를 체택하는게 좋다고 해야할까? ㅎㅎㅎ 개발입장이아닌 서비스 입장에는 비용이든다는게 흠이죠 ㅎㅎㅎ
변종원(웅파) / 2017/03/29 16:05:14 / 추천 0
테러보이/ 다음인가 해당 서비스를 api로 제공하고 있는 걸로 기억됩니다. ^^
테러보이 / 2017/03/29 16:48:35 / 추천 0
@웅파 앗! 그런가요? 찾아봐야겠네요 ㅎㅎ