Tokenizer API
The types and the functions of the package lindera for tokenizing: the dictionary and the user dictionary, the mode, the builder, the tokenizer and the tokens. What they share (who closes an object, how an error is returned, what goroutines may do) is in Lindera Go.
The examples load the dictionary embedded://ipadic, which names a dictionary a library was built with; with the library of a release it is the path of a directory.
Versions and features
| Name | What it is |
|---|---|
ModuleVersion | The version of the module, a constant string |
Version() string | The version of the library the program runs with |
HasFeature(name string) bool | Whether the library was built with a feature: "train", "dependency", "embed-<dictionary>" or "embed-dependency-<dictionary>". false for a name that is no feature |
Dictionary
A dictionary that is loaded.
| Function or method | What it does |
|---|---|
LoadDictionary(uri string) (*Dictionary, error) | Loads the dictionary at uri |
(*Dictionary).Name() string | The name the metadata of the dictionary records ("ipadic") |
(*Dictionary).Encoding() string | The character encoding the metadata records ("UTF-8") |
(*Dictionary).Close() error | Frees the dictionary |
uri is the path of a directory that holds a built dictionary, or embedded://<name> (for example embedded://ipadic) for a dictionary the library was built with. LoadDictionary fails with an error of the kind KindIO when the path does not exist, and of the kind KindDictionary when the library was not built with the embedded dictionary.
A dictionary that is loaded makes a tokenizer with NewTokenizer, and a user dictionary is loaded for it. A tokenizer that was made from the dictionary does not need it afterwards. The whole metadata of a dictionary (its Metadata method), with its schema, and building a dictionary are in Dictionary Management.
UserDictionary
A user dictionary: words a program adds to those of a dictionary.
| Function or method | What it does |
|---|---|
LoadUserDictionaryFor(uri string, dictionary *Dictionary) (*UserDictionary, error) | Loads the file at uri for dictionary |
(*UserDictionary).Close() error | Frees the user dictionary |
uri is the path of a .csv file, which is built with the metadata of the dictionary and checked against its connection matrix, or of a .bin file, a user dictionary that was built before. A line of a CSV that the dictionary cannot hold fails the call, and the message names the line and the surface (line 2 (surface: '東武スカイツリーライン')).
A line of the simplest CSV is a surface, a part of speech and a reading:
東京スカイツリー,カスタム名詞,トウキョウスカイツリー
A tokenizer is given the user dictionary when it is made, and has a copy of it:
userDictionary, err := lindera.LoadUserDictionaryFor(file, dictionary)
if err != nil {
log.Fatal(err)
}
defer userDictionary.Close()
tokenizer, err := lindera.NewTokenizer(dictionary, lindera.WithUserDictionary(userDictionary))
if err != nil {
log.Fatal(err)
}
defer tokenizer.Close()
tokens, err := tokenizer.Tokenize("東京スカイツリーの最寄り駅")
if err != nil {
log.Fatal(err)
}
for _, token := range tokens {
fmt.Printf("%s\t%s\n", token.Surface, token.Details[0])
}
With the line above, 東京スカイツリー is one token, whose first detail is カスタム名詞:
東京スカイツリー カスタム名詞
の 助詞
最寄り駅 名詞
Building a user dictionary into a .bin file, and loading one with a metadata in place of a dictionary (LoadUserDictionary), are in Dictionary Management.
Penalty and Mode
A tokenizer runs in the normal mode, or in the decompose mode, which prefers the shorter words a long word is made of. The decompose mode has a penalty: a word of more characters than a threshold costs the penalty for each character over it, and words of kanji alone have a threshold and a penalty of their own.
Penalty is a struct:
| Field | Type | Default | What it is |
|---|---|---|---|
KanjiPenaltyLengthThreshold | int | 2 | The number of characters over which a word of kanji alone is penalized |
KanjiPenaltyLengthPenalty | int32 | 3000 | The cost of each character of such a word over the threshold |
OtherPenaltyLengthThreshold | int | 7 | The number of characters over which another word is penalized |
OtherPenaltyLengthPenalty | int32 | 1700 | The cost of each character of such a word over the threshold |
Mode is a value, which does not change and holds nothing of the library; its zero value is the normal mode.
| Function | Returns |
|---|---|
DefaultPenalty() (Penalty, error) | The penalty with the default values, which are those of the library |
NormalMode() Mode | The normal mode |
DecomposeMode() Mode | The decompose mode with the default penalty |
DecomposeModeWithPenalty(penalty Penalty) Mode | The decompose mode with a penalty |
ParseMode(name string) (Mode, error) | The mode a name stands for, "normal" or "decompose" (with the default penalty); an error of the kind KindInvalidArgument for another name |
Method of Mode | Returns |
|---|---|
String() string | "normal" or "decompose" |
IsNormal() bool, IsDecompose() bool | Whether the mode is that one |
Penalty() (Penalty, bool) | The penalty of a decompose mode; false for the normal mode, which has none |
Equal(other Mode) bool | Whether two modes are both normal, or both decompose with the same penalty |
mode, err := lindera.ParseMode("decompose")
if err != nil {
log.Fatal(err)
}
fmt.Println(mode, mode.IsDecompose(), mode.Equal(lindera.DecomposeMode()))
penalty, ok := mode.Penalty()
fmt.Println(ok, penalty.KanjiPenaltyLengthThreshold, penalty.KanjiPenaltyLengthPenalty)
fmt.Println(penalty.OtherPenaltyLengthThreshold, penalty.OtherPenaltyLengthPenalty)
_, ok = lindera.NormalMode().Penalty()
fmt.Println(lindera.NormalMode(), ok)
decompose true true
true 2 3000
7 1700
normal false
A penalty that is not valid (a negative threshold) is reported where the mode is used: NewTokenizer fails, and a builder keeps the error. Such a mode equals none.
With IPADIC, 関西国際空港限定トートバッグ gives:
| Mode | Tokens |
|---|---|
| Normal | 関西国際空港 / 限定 / トートバッグ |
| Decompose, with the default penalty | 関西 / 国際 / 空港 / 限定 / トートバッグ |
Decompose, with OtherPenaltyLengthThreshold 4 and OtherPenaltyLengthPenalty 3000 | 関西 / 国際 / 空港 / 限定 / トー / トバッグ |
| Decompose, with both penalties 0 | 関西国際空港 / 限定 / トートバッグ |
The third row is this tokenizer:
penalty, err := lindera.DefaultPenalty()
if err != nil {
log.Fatal(err)
}
// A word that is not of kanji alone is long over 4 characters.
penalty.OtherPenaltyLengthThreshold = 4
penalty.OtherPenaltyLengthPenalty = 3000
tokenizer, err := lindera.NewTokenizerBuilder().
SetDictionary("embedded://ipadic").
SetMode(lindera.DecomposeModeWithPenalty(penalty)).
Build()
TokenizerBuilder
A builder collects the settings of a tokenizer. A builder is for one goroutine at a time.
Making and closing
| Function or method | What it does |
|---|---|
NewTokenizerBuilder() *TokenizerBuilder | Makes a builder with the default settings |
NewTokenizerBuilderFromFile(path string) (*TokenizerBuilder, error) | Makes a builder from a YAML configuration file |
(*TokenizerBuilder).Close() error | Frees the builder. The tokenizers it built do not need it |
Settings
Each of these methods returns the builder, so that the calls can be chained. None returns an error: the builder keeps the first one, does nothing after it, and Build returns it.
| Method | What it sets |
|---|---|
SetDictionary(uri string) | The dictionary: a path, or embedded://<name>. It is loaded when the tokenizer is built |
SetMode(mode Mode) | The mode. The default is the normal mode |
SetUserDictionary(uri string) | The user dictionary: the path of a .csv or of a .bin file. It is loaded when the tokenizer is built |
SetSpacePenaltyJSON(text string) | The left-space penalty (Korean), as JSON text: null or an empty text for the default (the rules the dictionary ships, if any), false for no penalty, true for the rules of the dictionary, which must ship some, or an object such as {"rules":[{"pos":["JKS"],"cost":6000}]} |
SetKeepWhitespace(keep bool) | Whether whitespace tokens are in the output. Kept whitespace also stays in the lattice, so the other tokens can differ from those of the default output |
SetSkipWhitespace(skip bool) | Whether whitespace is skipped in the lattice: true connects the words on either side directly, as MeCab does; false keeps the whitespace as a node of its own, which is still left out of the output. It has no effect while whitespace tokens are kept |
ResetSkipWhitespace() | Removes that setting, so that the default of the dictionary applies (skipping, except with SudachiDict) |
SetBreakCharacters(characters string) | The break characters: no unknown word, nor, in decompose mode, any word of the dictionary, crosses a boundary between one of them and another character. An empty text turns the rule off, which gives the segmentation of MeCab |
ResetBreakCharacters() | Removes that setting, so that the default (・) applies |
AppendCharacterFilter(kind string, args any) | Appends a character filter |
AppendTokenFilter(kind string, args any) | Appends a token filter |
kind is the name of a filter, and args its arguments: nil for none, or a Go value that encoding/json encodes as a JSON object (a map, or a struct with json tags). The filters run in the order they were appended. A name or arguments a filter does not accept are reported when the tokenizer is built. Text Processing Pipeline shows the filters at work, and all of them are listed with their arguments in Filters.
With IPADIC, the break characters and the skipping of whitespace give:
| Text | Setting | Tokens |
|---|---|---|
レノン・ジョン | Default (・ is a break character) | レノン / ・ / ジョン |
レノン・ジョン | SetBreakCharacters("") | レノン・ジョン |
Google が 新しい | Default (whitespace skipped) | が is a particle (助詞) |
Google が 新しい | SetSkipWhitespace(false) | が is a conjunction (接続詞) |
Building
| Method | What it does |
|---|---|
Build() (*Tokenizer, error) | Builds a tokenizer from the settings |
Err() error | The first error of the methods that set something, or nil |
The builder is not changed by Build and can build again; the tokenizer does not need it afterwards. Build returns the first error of the settings, if there is one, and fails when no dictionary is set, when the dictionary cannot be loaded, or when a setting or a filter is not valid.
Tokenizer
A tokenizer from a dictionary
NewTokenizer(dictionary *Dictionary, opts ...TokenizerOption) (*Tokenizer, error) makes a tokenizer from a dictionary that is loaded, without a builder. What it can be told and does not need is an option:
| Option | What it sets |
|---|---|
WithMode(mode Mode) | The mode. The default is the normal mode |
WithUserDictionary(userDictionary *UserDictionary) | A user dictionary. nil, which is the default, is none |
WithSpacePenaltyJSON(text string) | The left-space penalty, in the forms SetSpacePenaltyJSON takes. The default is the rules the dictionary ships, if any |
The tokenizer takes what it needs of the dictionary and of the user dictionary, which the program still closes, before or after the tokenizer.
A tokenizer made this way has no filters; a builder makes one with filters.
dictionary, err := lindera.LoadDictionary("embedded://ipadic")
if err != nil {
log.Fatal(err)
}
defer dictionary.Close()
tokenizer, err := lindera.NewTokenizer(dictionary, lindera.WithMode(lindera.DecomposeMode()))
if err != nil {
log.Fatal(err)
}
defer tokenizer.Close()
NewTokenizer fails with an error of the kind KindInvalidArgument for no dictionary (nil), and with ErrClosed for a dictionary or a user dictionary that is closed.
Tokenizing
| Method | What it does |
|---|---|
Tokenize(text string) ([]Token, error) | Tokenizes a text, and returns its tokens in the order of the text |
Close() error | Frees the tokenizer. It waits for the calls that are tokenizing |
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, ","))
}
The tokens are Go values: the result of the library is freed before Tokenize returns. A text without a token gives no token. Tokenize fails with an error of the kind KindInvalidArgument for a text that is not UTF-8, and with ErrClosed after Close.
Goroutines may tokenize with one tokenizer at the same time, and their calls run in parallel: see Lindera Go.
The other forms
| Method | Arguments | Returns |
|---|---|---|
Tokenize | text string | []Token |
TokenizeSurfaces | text string | []SurfaceToken |
TokenizeNBest | text string, n int, opts ...NBestOption | []NBestResult |
TokenizeBatch | texts []string, opts ...BatchOption | [][]Token |
TokenizeSurfacesBatch | texts []string, opts ...BatchOption | [][]SurfaceToken |
TokenizeNBestBatch | texts []string, n int, opts ...NBestBatchOption | [][]NBestResult |
Each returns an error as its second value. The options are:
| Option | Of | What it does |
|---|---|---|
WithUnique() | The N best | Leaves out a tokenization whose word boundaries are those of one before it |
WithCostThreshold(threshold int64) | The N best | Leaves out the tokenizations that cost more than the best one plus threshold |
WithMaxThreads(n int) | Several texts | The most threads the call runs on. 0, which is the default, is the number of threads the system reports |
TokenizeNBestBatch takes the options of both.
The surfaces alone. TokenizeSurfaces gives the surface and the position of each token, without the details: the fast way for a program that needs the words and no part of speech. The surfaces are those Tokenize gives.
surfaces, err := tokenizer.TokenizeSurfaces("関西国際空港限定トートバッグ")
if err != nil {
log.Fatal(err)
}
for _, surface := range surfaces {
fmt.Println(surface.Surface, surface.ByteStart, surface.ByteEnd)
}
関西国際空港 0 18
限定 18 24
トートバッグ 24 42
The N best. TokenizeNBest gives up to n tokenizations, the best first, each with its cost. The first is the one Tokenize gives.
results, err := tokenizer.TokenizeNBest("東京都に住む", 3, lindera.WithUnique())
if err != nil {
log.Fatal(err)
}
for _, result := range results {
var surfaces []string
for _, token := range result.Tokens {
surfaces = append(surfaces, token.Surface)
}
fmt.Println(result.Cost, strings.Join(surfaces, " "))
}
6327 東京 都 に 住む
11287 東 京都 に 住む
20019 東 京 都 に 住む
Without WithUnique, the third tokenization of this text has the words of the first, with other details.
Several texts. The batch forms tokenize each text as the form for one text does, on threads of the library, and return one list for each text, in the order of the texts. The first text that fails, in that order, fails the call, and the message names it by its index (texts[2] is not valid UTF-8).
texts := []string{"関西国際空港限定トートバッグ", "東京都に住む"}
batch, err := tokenizer.TokenizeBatch(texts, lindera.WithMaxThreads(2))
if err != nil {
log.Fatal(err)
}
for i, tokens := range batch {
fmt.Println(texts[i], len(tokens))
}
関西国際空港限定トートバッグ 3
東京都に住む 4
Every text is tokenized as a call of its own: a slice of the lines of a document gives the tokens of each line, not those of the whole document as one text. A short slice runs on one thread (a thread needs at least 16 KiB of input), and every thread holds its own copy of the user dictionary, if any.
The threads tokenize the texts; the result is put together, and copied into Go values, on the goroutine that called. For a large input, goroutines that each call Tokenize use the CPUs better than one batch does: see Lindera Go.
A batch already runs on several threads, so the batches of one tokenizer take turns: a batch that starts while another runs waits for it. The calls that tokenize one text do not wait for a batch.
Token
| Field | Type | What it is |
|---|---|---|
Surface | string | The surface form |
ByteStart | int | Where the token starts in the text, in bytes |
ByteEnd | int | Where the token ends in the text (exclusive), in bytes |
Position | int | The position of the token among the tokens, from 0 |
Details | []string | The details: the fields of the word in the dictionary (the part of speech, the reading and so on) |
WordID | uint32 | The ID of the word in the dictionary |
Unknown | bool | Whether the word is not in the dictionary |
Dependency | *Dependency | The dependency of the token, or nil unless the token filter japanese_dependency wrote one |
A word that is not in the dictionary has the details of its line of the unknown word definition (名詞,一般,*,*,*,*,*,*,* for a katakana word with IPADIC).
The strings of the tokens of a text are parts of one copy of the bytes of the result, so a string that is kept keeps the bytes of its text alive; strings.Clone makes a string that stands alone. In a batch each text has a copy of its own, and so has each of the N best tokenizations.
SurfaceToken and NBestResult
Field of SurfaceToken | Type | What it is |
|---|---|---|
Surface | string | The surface form |
ByteStart | int | Where the token starts in the text, in bytes |
ByteEnd | int | Where the token ends in the text (exclusive), in bytes |
Field of NBestResult | Type | What it is |
|---|---|---|
Tokens | []Token | The tokens of this tokenization |
Cost | int64 | Its cost: the lower, the better |
Dependency
What the token filter japanese_dependency writes: the bunsetsu of a token, and the bunsetsu that one depends on. See Token Filter for the filter and its model.
| Field | Type | What it is |
|---|---|---|
Score | float64 | The score of the decision that attached the bunsetsu to its head |
Sentence | int | The number of the sentence in the text, from 0 |
Bunsetsu | int | The number of the bunsetsu of the token in its sentence, from 0 |
Head | int | The number of the bunsetsu that one depends on, or NoHead for the last bunsetsu of a sentence |
Role | BunsetsuRole | What the token is in its bunsetsu: RoleHead, RoleFunction, RoleHeadFunction or RoleOther |
The String method of a BunsetsuRole returns the name of the role: "head", "function", "head_function" or "other".
The filter takes the path of a model file as its argument: AppendTokenFilter("japanese_dependency", map[string]any{"model": "/path/to/ipadic.model"}).