end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

kuromoji.js - javascript版 形態素解析

python版の形態素解析は、以前、上記entryにある sudachipy を使用しましたが、 今回は、javascript版の形態素解析である kuromoji.js を node.jsを用いず、ブラウザで動作させます。

github.com

https://github.com/takuyaa/kuromoji.js にある 「Browser You only need the build/kuromoji.js and dict/*.dat.gz files」の通り、 これらをダウンロードし、以下のhtml + javascriptを作成

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8"/>
<style>
table  { border-collapse: collapse; }
th, td { border: 1px solid #555;  padding: 5px; }
</style>
</head>
<body>
  <input id="org_text" type="text" style="width:400px;"
         value="ここに形態素解析対象の文を入力してください。"/>
  <button type="button" onClick="do_tokenize()">形態素解析</button>
  <table>
    <thead>
      <tr>
        <th>word_id</th><th>word_type</th><th>word_position</th>
        <th>surface_form</th><th>pos</th><th>固有値</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  
  <template id="tmpl_tr">
    <tr> <td></td><td></td><td></td><td></td><td></td><td></td> </tr>
  </template>
  
  <script src="./kuromoji.js"></script>
  <script>
    function buildTokenizer() {
        return new Promise((resolve, reject) => {
            kuromoji.builder({ dicPath: "./dict" }).build((err,tokenizer)=>{
                if (err) {
                    reject(err);
                } else {
                    resolve(tokenizer);
                }
            });
        });
    }
    let tokenizer;
    let org_txt_elm = document.querySelector("#org_text");
    let tmpl_tr     = document.querySelector("#tmpl_tr");
    let tbody       = document.querySelector("table tbody");
    
    function do_tokenize() {
        let org_text = org_txt_elm.value.trim();
        let tokens = tokenizer.tokenize(org_text);
        tbody.innerHTML = "";
        
        for (let token of tokens ){
            //"true" is "deep copy".
            let clone = tmpl_tr.content.cloneNode(true);
            let tds = clone.querySelectorAll("td");
            tds[0].textContent = token["word_id"];
            tds[1].textContent = token["word_type"];
            tds[2].textContent = token["word_position"];
            tds[3].textContent = token["surface_form"];
            tds[4].textContent = token["pos"];

            if(token.pos == "名詞" && token.pos_detail_1 == "固有名詞"){
                tds[5].textContent = "固有表現";
            }
            tbody.appendChild(clone);
        }
    }

    async function main() {
        tokenizer = await buildTokenizer();
    }
    
    main();
  </script>
</body>
</html>

すると、以下のように表示され、実行できます