node에서 python의 형태소 분석기를 호출하는 과정
-- 한글의 경우 print에서 깨짐이 발생하므로, 인코딩과정을 추가하였다.
-- python에서 형태소 분석 결과를 print로 출력하면, node에서 출력된 string을 객체로 파싱한다.
JSON.parse를 사용하려고 했지만, 파이썬에서 single quotation을 사용하기 때문에 JSON으로 포맷을 맞추지 못해서, 어쩔 수 없이 eval을 사용했다.
test.js
const {PythonShell} = require('python-shell');
 
let options = {
  mode: 'text',
  pythonPath: 'C:\\Users\\.....\\Anaconda3\\python.exe',
  pythonOptions: ['-u'],
  scriptPath: 'F:\\........\\python',
  args: ['사과에 대한 시장수요곡선은'],
  encoding: 'utf8'
};
 
PythonShell.run('my2.py', options, function (err, results) {
  if (err) throw err;
  let data = results[0].replace(`b\'`, '').replace(`\'`, '');
  let buff = Buffer.from(data, 'base64');
  let text = buff.toString('utf-8');
  console.log('text:', text);
  const list = eval('(' + text + ')');
  console.log('list.length, list', list.length, list)
});
my2.py
import base64
import sys
from konlpy.tag import Kkma
kkma = Kkma()
result = kkma.nouns(sys.argv[1])
result = str(result)
print(base64.b64encode(result.encode('utf-8')))
cmd> node test.js
콘솔 결과
text: ['사과', '시장', '시장수요곡선', '수요', '곡선']
list.length, list 5 [ '사과', '시장', '시장수요곡선', '수요', '곡선' ]'web > node.js' 카테고리의 다른 글
| simple express (0) | 2021.09.26 | 
|---|---|
| lerna test (0) | 2021.06.13 |