Ribbit's works

kuromoji.jsで形態素解析

#TypeScript #JavaScript
にメンテナンス済み
記事のトップ画像

今回は形態素解析が簡単に実行できるライブラリ「kuromoji.js」を使って、任意の文字列を品詞ごとに分解・解析する方法を紹介します。

インストール

npm install kuromoji

使い方

辞書を読み込む

kuromoji のインスタンスを作成するタイミングで、辞書を指定する必要があります。 インストール時にデフォルトの辞書も入っているので、特別指定が無ければこれを使用すればよいと思います。

import { builder, IpadicFeatures, TokenizerBuilder } from 'kuromoji';

const defaultBuilder = builder({ dicPath: 'node_modules/kuromoji/dict' });

解析を実行

解析には作成したインスタンスの build 関数を使用します。 build 関数は引数にコールバック関数を指定し、コールバック関数から Tokenizer を受け取ることができます。 Tokenizer.tokenize の引数に解析したい文字列を指定することで、形態素解析が実行されます。

/** 解析する文字列 */
const target = '月がきれいですね。';

defaultBuilder.build((err, tokenizer) => {
  if (err) {
    console.error(err);
  }
  console.log(tokenizer.tokenize(target));
});

解析結果

結果は以下のようなオブジェクトの配列で返却されます。

[
  {
    word_id: 461780,
    word_type: 'KNOWN',
    word_position: 1,
    surface_form: '月',
    pos: '名詞',
    pos_detail_1: '一般',
    pos_detail_2: '*',
    pos_detail_3: '*',
    conjugated_type: '*',
    conjugated_form: '*',
    basic_form: '月',
    reading: 'ツキ',
    pronunciation: 'ツキ',
  },
  {
    word_id: 92920,
    word_type: 'KNOWN',
    word_position: 2,
    surface_form: 'が',
    pos: '助詞',
    pos_detail_1: '格助詞',
    pos_detail_2: '一般',
    pos_detail_3: '*',
    conjugated_type: '*',
    conjugated_form: '*',
    basic_form: 'が',
    reading: 'ガ',
    pronunciation: 'ガ',
  },
  {
    word_id: 111840,
    word_type: 'KNOWN',
    word_position: 3,
    surface_form: 'きれい',
    pos: '名詞',
    pos_detail_1: '形容動詞語幹',
    pos_detail_2: '*',
    pos_detail_3: '*',
    conjugated_type: '*',
    conjugated_form: '*',
    basic_form: 'きれい',
    reading: 'キレイ',
    pronunciation: 'キレイ',
  },
  {
    word_id: 23760,
    word_type: 'KNOWN',
    word_position: 6,
    surface_form: 'です',
    pos: '助動詞',
    pos_detail_1: '*',
    pos_detail_2: '*',
    pos_detail_3: '*',
    conjugated_type: '特殊・デス',
    conjugated_form: '基本形',
    basic_form: 'です',
    reading: 'デス',
    pronunciation: 'デス',
  },
  {
    word_id: 92590,
    word_type: 'KNOWN',
    word_position: 8,
    surface_form: 'ね',
    pos: '助詞',
    pos_detail_1: '終助詞',
    pos_detail_2: '*',
    pos_detail_3: '*',
    conjugated_type: '*',
    conjugated_form: '*',
    basic_form: 'ね',
    reading: 'ネ',
    pronunciation: 'ネ',
  },
  {
    word_id: 90940,
    word_type: 'KNOWN',
    word_position: 9,
    surface_form: '。',
    pos: '記号',
    pos_detail_1: '句点',
    pos_detail_2: '*',
    pos_detail_3: '*',
    conjugated_type: '*',
    conjugated_form: '*',
    basic_form: '。',
    reading: '。',
    pronunciation: '。',
  },
];

処理にあたって

コールバック関数を使う仕様上、async/await と相性が良くないため、以下のように Promise に対応させておくと便利かもしれません。

const getTokenizer = (
  builder: TokenizerBuilder<IpadicFeatures>
): Promise<Tokenizer<IpadicFeatures>> => {
  return new Promise((resolve, reject) => {
    builder.build((err, tokenizer) => {
      if (err) {
        reject(err);
      }
      resolve(tokenizer);
    });
  });
};