Help us understand the problem. What is going on with this article?

kagomeでの形態素解析にユーザ辞書を使う雑なサンプル

More than 1 year has passed since last update.

kagomeで形態素解析をするときユーザ辞書を使うサンプル。

とりあえずコード

import "github.com/ikawaha/kagome/tokenizer"

func Tokenize() {
    t := tokenizer.New()

    // bindataから辞書ファイルを取得
    dic, _ := Asset("dic.txt")

    // ユーザ辞書を設定
    userDicRecords, _ := tokenizer.NewUserDicRecords(bytes.NewReader(dic))
    userDic, _ := userDicRecords.NewUserDic()
    t.SetUserDic(userDic)

    tokens := t.Tokenize("cとc++とc#とobjective-c")
    for _, token := range tokens {
        if token.Class == tokenizer.DUMMY {
            // BOS or EOS
            continue
        }
        fmt.Println(token)
    }
}

辞書を設定せずにコードを実行した場合の出力は以下のようになる。見事に分解されてしまっているのでcとc++とc#とobjective-cが単語として判定されるようにユーザ辞書を設定したい。

c(0, 1)UNKNOWN[5]
と(1, 2)KNOWN[47729]
c(2, 3)UNKNOWN[5]
++(3, 5)UNKNOWN[39]
と(5, 6)KNOWN[47729]
c(6, 7)UNKNOWN[5]
#(7, 8)UNKNOWN[39]
と(8, 9)KNOWN[47729]
objective(9, 18)UNKNOWN[5]
-(18, 19)UNKNOWN[39]
c(19, 20)UNKNOWN[5]

辞書データはこんな感じ。狙ったとおりに単語を分解したい、という需要なら至極簡単でいい。

dic.txt
c,c,,名詞
objective-c,objective-c,,名詞
c#,c#,,名詞
c++,c++,,名詞

これで結果はこうなる

c(0, 1)USER[0]
と(1, 2)KNOWN[47727]
c++(2, 5)USER[2]
と(5, 6)KNOWN[47727]
c#(6, 8)USER[1]
と(8, 9)KNOWN[47727]
objective-c(9, 20)USER[3]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした