kuromoji.js による 日本語形態素解析 を試す
「kuromoji.js」による「日本語形態素解析」を試したので、まとめました。
1. kuromoji.js
「kuromoji.js」は、日本語形態素解析器のJavaScript 実装です。「kuromoji」の純粋なJavaScript移植版になります。
2. kuromoji.js の使用
「kuromoji.js」の使用手順は、次のとおりです。
(1) プロジェクトの準備。
Node.jsをインストール後、TypeScriptプロジェクトを準備します。
$ mkdir helloworld
$ cd helloworld
$ npm init -y
$ npm install typescript --save-dev
$ npx tsc --init
(2) 「kuromoji.js」パッケージのインストール。
$ npm install kuromoji @types/kuromoji
(3) ソースコード「index.ts」の準備。
今回は、「固有表現抽出」を行います。
・index.ts
import * as kuromoji from "kuromoji";
// トークナイザーのビルド
function buildTokenizer() {
return new Promise<kuromoji.Tokenizer<kuromoji.IpadicFeatures>>((resolve, reject) => {
kuromoji.builder({ dicPath: "node_modules/kuromoji/dict" }).build((err, tokenizer) => {
if (err) {
reject(err);
} else {
resolve(tokenizer);
}
});
});
}
async function main() {
// トークナイザーのビルド
const tokenizer = await buildTokenizer();
// 解析するテキスト
const text = "田中一郎は静岡に行くため東京駅に向かいました。";
// 形態素解析の実行
const tokens = tokenizer.tokenize(text);
// 固有表現抽出の実行
const properNouns = tokens.filter(
token => token.pos === "名詞" && token.pos_detail_1 === "固有名詞");
console.log(properNouns);
}
main();
(4) コンパイルと実行。
$ npx tsc
$ node index.js
[
{
word_id: 919900,
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: 2035250,
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: 3245930,
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: 3029410,
word_type: 'KNOWN',
word_position: 13,
surface_form: '東京',
pos: '名詞',
pos_detail_1: '固有名詞',
pos_detail_2: '地域',
pos_detail_3: '一般',
conjugated_type: '*',
conjugated_form: '*',
basic_form: '東京',
reading: 'トウキョウ',
pronunciation: 'トーキョー'
}
]
この記事が気に入ったらサポートをしてみませんか?