node.js 版の kuromoji で形態素解析をしてみました。
今回は TypeScript で kuromoji を使います。
kuromoji のインストール方法は以下の通りです。
npm install kuromoji
npm install @types/kuromoji
kuromoji を使いやすくするため、以下のようにライブラリ化しました。
■KuromojiUtil.ts
/**
* Kuromoji Util
*/
import kuromoji, { Tokenizer, IpadicFeatures, TokenizerBuilder } from 'kuromoji';
export default class KuromojiUtil {
private constructor() {}
public static getTokenizer(paramh: any): Promise<Tokenizer<IpadicFeatures>> {
const builder: TokenizerBuilder<IpadicFeatures> =
kuromoji.builder(paramh);
return new Promise<Tokenizer<IpadicFeatures>>(done => {
builder.build((err, tknzr) => {
done(tknzr);
});
});
}
}
上記の KuromojiUtil.ts を使って形態素解析を行います。
import KuromojiUtil from './KuromojiUtil';
(async () => {
const paramh = {
dicPath: 'node_modules/kuromoji/dict',
};
const tknzr = await KuromojiUtil.getTokenizer(paramh);
const text = '日本語の文です';
const tkns = tknzr.tokenize(text);
console.log(tkns);
})();
■実行結果
[
{
word_id: 2591070,
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: 93100,
word_type: 'KNOWN',
word_position: 4,
surface_form: 'の',
pos: '助詞',
pos_detail_1: '連体化',
pos_detail_2: '*',
pos_detail_3: '*',
conjugated_type: '*',
conjugated_form: '*',
basic_form: 'の',
reading: 'ノ',
pronunciation: 'ノ'
},
{
word_id: 2475380,
word_type: 'KNOWN',
word_position: 5,
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: 'デス'
}
]