LoginSignup
24
23

More than 5 years have passed since last update.

GAE/Goで形態素解析してみた

Last updated at Posted at 2016-05-17

GAE/Goで形態素解析

Goの形態素解析ライブラリで最もメジャーなのはkagomeであるが、辞書ファイルが1ファイルの容量制限(32MB)を超えてしまい、デプロイできない。
そこで、他にもGoで書かれた形態素解析のコードはないものかと探し回ったら、SenKoというのが存在したので、試してみました。

SenKo

MeCab形式の辞書ファイル(csv)を採用。
32MBを超えるcsvファイルは存在しないが、辞書ファイルが多いい。

試してみるコード

辞書の読み込み

var dec *senko.Decoder
func loadDictionary() {
    mat := senko.LoadMatrix("data/matrix.def")
    dict := senko.NewDictionary()
    dict.LoadDictionaries("data")
    dec = senko.NewDecoder(dict, mat)
}

APIの作成

リクエスト:形態素解析したい文章
レスポンス:形態素解析結果(単語・品詞)

func registerAnalysis() {
    http.HandleFunc("/api/analysis", handleAnalysis)
}

func handleAnalysis(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    sentence := r.FormValue("sentence")
    log.Infof(c, "形態素解析対象文字列 = %s\n", sentence)
    var vocabularies []Vocabulary
    for _, s := range dec.Search(sentence) {
        str := strings.Split(s.Repr(), ",")
        if str[0] == "EOS" {
            break
        }
        vocabulary := Vocabulary{
            Word: str[0],
            Pos:  str[4],
        }
        vocabularies = append(vocabularies, vocabulary)
        log.Infof(c, "単語 = %s, 品詞 = %s", vocabulary.Word, vocabulary.Pos)
    }
    json, err := json.Marshal(&vocabularies)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    w.Header().Set("Content-Type", "application/json;charset=utf-8")
    w.Write(json)
}

デプロイしてみる

動いた。
kagomeに比べ、csvファイルを読み込む処理が入るのでTokenizerの生成に時間はかかるが、一度読み込んでしまえば、形態素解析の処理自体は速いです。
文章の中に未知語が含まれていると、結果を返してくれなかったり、kagomeよりも精度は劣ると感じるものの、自分がやりたいことに対しては十分でした。
辞書ファイルがcsvなので、必要に応じて楽に単語を追加できる点でもありだとは思います。

スクリーンショット 2016-05-17 18.35.19.png

最後の「もも」がうまくいっていませんね(涙)

24
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23