dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

Typescript で MeCab で形態素解析

2022-01-13 21:04:58 | Node.js
Typescript で MeCab で形態素解析する方法のメモ。
TypeScript で MeCab を実行するのに mecab-client を使用します。

■MeCab のインストール
yum install mecab mecab-ipadic

■mecab-client のインストール
npm install mecab-client

■mecab-client を利用したサンプルプログラム
import { MeCab } from 'mecab-client';

async function main() {
  const tknzr = new MeCab();
  const str = '私は人間です。';

  const tkns = await tknzr.parse(str);
  for (let tkn of tkns) {
    console.log(tkn);
  }
}

main();

■実行結果
解析結果は token のリストで返却されます。
{ surface: '私',
  lexical: '名詞',
  compound1: '代名詞',
  compound2: '一般',
  compound3: '*',
  conjugation: '*',
  inflection: '*',
  original: '私',
  reading: 'ワタシ',
  pronunciation: 'ワタシ' }
{ surface: 'は',
  lexical: '助詞',
  compound1: '係助詞',
  compound2: '*',
  compound3: '*',
  conjugation: '*',
  inflection: '*',
  original: 'は',
  reading: 'ハ',
  pronunciation: 'ワ' }
{ surface: '人間',
  lexical: '名詞',
  compound1: '一般',
  compound2: '*',
  compound3: '*',
  conjugation: '*',
  inflection: '*',
  original: '人間',
  reading: 'ニンゲン',
  pronunciation: 'ニンゲン' }
{ surface: 'です',
  lexical: '助動詞',
  compound1: '*',
  compound2: '*',
  compound3: '*',
  conjugation: '特殊・デス',
  inflection: '基本形',
  original: 'です',
  reading: 'デス',
  pronunciation: 'デス' }
{ surface: '。',
  lexical: '記号',
  compound1: '句点',
  compound2: '*',
  compound3: '*',
  conjugation: '*',
  inflection: '*',
  original: '。',
  reading: '。',
  pronunciation: '。' }