Quick Start

This guide shows how to tokenize text from a Go program with Lindera Go.

Basic Tokenization

The program below is lindera-go/examples/tokenize/main.go. It builds a tokenizer through a builder, tokenizes a text, and prints each token with its details:

// Tokenizes a text and prints each token with its details, one per line, as
// `lindera tokenize` does.
//
//	tokenize <dictionary> [<text>]
//
// <dictionary> is the path of a directory that holds a built dictionary, or
// "embedded://<name>" for a dictionary the library was built with. <text> is
// UTF-8.
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/lindera/lindera/lindera-go/v7"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintln(os.Stderr, "usage: tokenize <dictionary> [<text>]")
		os.Exit(2)
	}
	text := "関西国際空港限定トートバッグ"
	if len(os.Args) > 2 {
		text = os.Args[2]
	}
	if err := tokenize(os.Args[1], text); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func tokenize(dictionary, text string) error {
	// A builder collects the settings; the tokenizer is built from them.
	tokenizer, err := lindera.NewTokenizerBuilder().
		SetDictionary(dictionary).
		Build()
	if err != nil {
		return err
	}
	defer tokenizer.Close()

	// The tokens are Go values: there is nothing to free after them.
	tokens, err := tokenizer.Tokenize(text)
	if err != nil {
		return err
	}
	for _, token := range tokens {
		fmt.Printf("%s\t%s\n", token.Surface, strings.Join(token.Details, ","))
	}
	fmt.Println("EOS")
	return nil
}

Build it in a module that requires github.com/lindera/lindera/lindera-go/v7, with the library installed (see Installation), and run it with the path of a dictionary:

export PKG_CONFIG_PATH="$PWD/lindera-c-x86_64-unknown-linux-gnu-<version>/lib/pkgconfig"
go build -o tokenize .
./tokenize /path/to/lindera-ipadic

Note: Download a pre-built dictionary from GitHub Releases and specify the path to the extracted directory.

Expected output:

関西国際空港    名詞,固有名詞,組織,*,*,*,関西国際空港,カンサイコクサイクウコウ,カンサイコクサイクーコー
限定    名詞,サ変接続,*,*,*,*,限定,ゲンテイ,ゲンテイ
トートバッグ    名詞,一般,*,*,*,*,*,*,*
EOS

A second argument is the text:

./tokenize /path/to/lindera-ipadic 東京都に住む
東京    名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トーキョー
都      名詞,接尾,地域,*,*,*,都,ト,ト
に      助詞,格助詞,一般,*,*,*,に,ニ,ニ
住む    動詞,自立,*,*,五段・マ行,基本形,住む,スム,スム
EOS

What the program does

  1. It builds a tokenizer. A builder collects the settings (here the dictionary alone), and Build makes the tokenizer. The methods of the builder are chained: a setting that fails is reported by Build.
  2. It tokenizes. Tokenize returns the tokens as a slice of Go values. The result of the library is freed before Tokenize returns, so there is nothing to free after the tokens.
  3. It closes the tokenizer. Close frees the memory of the library the tokenizer holds.

Each call that can fail returns an error. The program prints it, with the kind of the failure and the message of the library:

lindera: parse: LinderaError(kind=Parse, source=failed to build tokenizer: LinderaError(kind=Io, source=Dictionary path does not exist: /no/such/dictionary))

Accessing Token Properties

A token is a struct, with its place in the text and the fields of its word in the dictionary:

token := tokens[0]
fmt.Println("Surface:", token.Surface)
fmt.Println("Byte range:", token.ByteStart, token.ByteEnd)
fmt.Println("Position:", token.Position)
fmt.Println("Unknown:", token.Unknown)
fmt.Println("Details:", len(token.Details))
fmt.Println("Part of speech:", token.Details[0])

For the first token of 東京都 with IPADIC, this prints:

Surface: 東京
Byte range: 0 6
Position: 0
Unknown: false
Details: 9
Part of speech: 名詞

WordID is the ID of the word in the dictionary, and Dependency what the token filter japanese_dependency wrote, or nil without it.

Filters

Character filters and token filters are appended to the builder. Their arguments are a Go value that becomes a JSON object (a map, or a struct with json tags), or nil for none:

tokenizer, err := lindera.NewTokenizerBuilder().
	SetDictionary("embedded://ipadic").
	AppendCharacterFilter("unicode_normalize", map[string]any{"kind": "nfkc"}).
	AppendTokenFilter("lowercase", nil).
	Build()

With these two, LINDERA is one token, lindera. (embedded://ipadic names the dictionary a library was built with; with the library of a release it is the path of a directory.)

Text Processing Pipeline shows more filters, and a pipeline of several.

Goroutines

One tokenizer serves the goroutines of a program: their calls of Tokenize run in parallel, and the tokenizer does not have to be made again for each of them. See Lindera Go.

The rest of the API

Tokenizer API has the modes, the user dictionaries, a tokenizer made from a dictionary that is loaded, and the other forms of tokenizing: the surfaces alone, the N best tokenizations, and several texts in one call. Dictionary Management has building a dictionary and a user dictionary, the metadata and the schema, and Training has training a dictionary from a corpus.