Tokenizer API
The types of the package Lindera that tokenize: the dictionary, the user dictionary, the mode, the builder, the tokenizer and the tokens. Lindera .NET has what they share: lifetimes, offsets, errors and threads.
What a method can be told and does not need is in an options type (TokenizerOptions, NBestOptions, BatchOptions), whose properties are init-only and default to what the library does; null is the defaults.
Versions and features
Member of LinderaLibrary | What it gives |
|---|---|
Version | The version of the library the program runs with |
PackageVersion | The version of the package, which is the version of Lindera it goes with |
HasFeature(string name) | Whether the library was built with a feature: "train", "dependency", "embed-ipadic" and so on |
Dictionary
| Member | What it does |
|---|---|
static Dictionary Load(string uri) | Loads a dictionary: the path of a directory that holds a built dictionary, or embedded://<name> for a dictionary the library was built with |
Name, Encoding | The name and the encoding of the dictionary, from its metadata |
GetMetadata() | A copy of the metadata of the dictionary (Dictionary Management) |
Dispose() | Frees the dictionary |
A path that does not exist is a LinderaException of the kind IO, and an embedded dictionary the library does not have one of the kind Dictionary.
UserDictionary
| Member | What it does |
|---|---|
static UserDictionary LoadFor(string uri, Dictionary dictionary) | Loads a user dictionary for a dictionary: the path of a CSV file of words, built with the metadata of the dictionary, or of a built user dictionary. The context IDs of its words are checked against the connection matrix of the dictionary |
static UserDictionary Load(string uri, Metadata metadata) | Loads a user dictionary with a metadata, without checking the context IDs of a CSV (Dictionary Management) |
Dispose() | Frees the user dictionary |
A tokenizer made with a user dictionary keeps a copy of it, so the user dictionary can be disposed before the tokenizer.
Penalty and Mode
Mode is the mode of a tokenizer: the normal mode, which takes the words of the dictionary as they are, or the decompose mode, which prefers the shorter words a long word is made of. Penalty is the penalty of the decompose mode: what a word longer than a threshold costs, for the words of kanji and for the others.
| Member | What it gives |
|---|---|
Mode.Normal | The normal mode, which is also the default value of Mode |
Mode.Decompose | The decompose mode with the default penalty of the library |
Mode.DecomposeWith(Penalty penalty) | The decompose mode with a penalty |
Mode.Parse(string name) | The mode a name stands for, normal or decompose, as the library reads it; another name is a LinderaException of the kind InvalidArgument |
IsNormal, IsDecompose | Which mode it is |
Penalty | The penalty of a decompose mode (the default of the library for Mode.Decompose), or null for the normal mode |
ToString() | The name the library gives the mode |
Equals, ==, != | Whether two modes are the same, as the library compares them: both normal, or both decompose with the same penalty |
Penalty.Default | The default penalty of the library |
Mode mode = Mode.Parse("decompose");
Console.WriteLine($"{mode} {mode.Penalty}");
Penalty shortKatakana = Penalty.Default with { OtherPenaltyLengthThreshold = 4, OtherPenaltyLengthPenalty = 3000 };
Mode custom = Mode.DecomposeWith(shortKatakana);
Console.WriteLine(custom == Mode.Decompose);
This prints:
decompose Penalty { KanjiPenaltyLengthThreshold = 2, KanjiPenaltyLengthPenalty = 3000, OtherPenaltyLengthThreshold = 7, OtherPenaltyLengthPenalty = 1700 }
False
A mode is a value, which holds nothing of the library. A penalty with a negative threshold is refused, with an ArgumentOutOfRangeException, where the mode is used (SetMode, Tokenizer.Create).
With IPADIC, 関西国際空港限定トートバッグ gives 関西国際空港 / 限定 / トートバッグ in the normal mode, 関西 / 国際 / 空港 / 限定 / トートバッグ in the decompose mode, and 関西 / 国際 / 空港 / 限定 / トー / トバッグ with the penalty shortKatakana above.
TokenizerBuilder
Making and disposing
| Member | What it does |
|---|---|
new TokenizerBuilder() | A builder with the settings of the library: the normal mode, no filters, and no dictionary yet |
static TokenizerBuilder FromFile(string path) | A builder with the settings of a configuration file (YAML or JSON), as the CLI of Lindera reads it |
Dispose() | Frees the builder; the tokenizers it built do not need it |
Settings
The setters return the builder, so that they follow each other, and throw at once when the library refuses a value.
| Method | What it sets |
|---|---|
SetMode(Mode mode) | The mode |
SetDictionary(string uri) | The dictionary, loaded by Build |
SetUserDictionary(string uri) | The user dictionary: the path of a CSV file or of a built user dictionary, loaded by Build |
SetSpacePenaltyJson(string json) | The left-space penalty (Korean), as JSON: false for none, true for the rules the dictionary ships, or an object such as {"rules":[{"pos":["JKS"],"cost":6000}]}; null or an empty text is the default of the dictionary |
SetKeepWhitespace(bool keep) | Whether the tokens keep the whitespace of the text |
SetSkipWhitespace(bool skip), ResetSkipWhitespace() | Whether whitespace is skipped before the tokenization, instead of the default of the dictionary |
SetBreakCharacters(string characters), ResetBreakCharacters() | The characters that break a run of unknown words |
AppendCharacterFilter(string kind, string? argsJson = null), AppendTokenFilter(string kind, string? argsJson = null) | A filter, by its name, with its arguments as a JSON object (Text Processing Pipeline) |
Building
Build() loads the dictionary and the user dictionary, makes the filters, and returns a Tokenizer. The builder can build again, and be changed. No dictionary, a dictionary that cannot be loaded, and a filter that cannot be made with its arguments are a LinderaException.
Tokenizer
A tokenizer from a dictionary
Tokenizer.Create(Dictionary dictionary, TokenizerOptions? options = null) makes a tokenizer from a dictionary that is loaded, without a builder. The options are the mode (Mode), a user dictionary (UserDictionary) and the left-space penalty (SpacePenaltyJson). The tokenizer takes what it needs of the dictionary and of the user dictionary, which can be disposed before it. It has no filters; a builder makes one with filters.
using Dictionary dictionary = Dictionary.Load("embedded://ipadic");
using UserDictionary userDictionary = UserDictionary.LoadFor(userDictionaryFile, dictionary);
using Tokenizer tokenizer = Tokenizer.Create(dictionary, new TokenizerOptions
{
Mode = Mode.Decompose,
UserDictionary = userDictionary,
});
Console.WriteLine(string.Join(" / ", tokenizer.Tokenize("東京スカイツリーは関西国際空港の東です").Select(t => t.Surface)));
With the user dictionary of the repository (resources/user_dict/ipadic_simple_userdic.csv), this prints:
東京スカイツリー / は / 関西 / 国際 / 空港 / の / 東 / です
Tokenizing
Tokenize(string text) returns the tokens of a text, in the order of the text, as .NET values. A text without a token gives none.
The other forms
| Method | What it returns |
|---|---|
TokenizeSurfaces(string text) | The surfaces of the tokens alone (SurfaceToken), with where they are, without their details: the fast way for a program that needs the words and no part of speech |
TokenizeNBest(string text, int n, NBestOptions? options = null) | Up to n best tokenizations (NBestResult), the best first, each with its cost. Unique leaves out a tokenization whose word boundaries are those of one before it, and CostThreshold the ones that cost more than the best plus it |
TokenizeBatch(IReadOnlyList<string> texts, BatchOptions? options = null) | The tokens of each text, in the order of the texts: for each text what Tokenize gives |
TokenizeSurfacesBatch(IReadOnlyList<string> texts, BatchOptions? options = null) | The surfaces of each text |
TokenizeNBestBatch(IReadOnlyList<string> texts, int n, NBestOptions? nbest = null, BatchOptions? options = null) | The N best tokenizations of each text |
The methods that tokenize several texts run on threads of the library: MaxThreads is their number, and 0, the default, is the number of threads the system reports. The calls of one tokenizer that tokenize several texts take turns, on one tokenizer of the library, which keeps its threads. A failure on one text fails the call: the first text that fails, in the order of the texts. A negative n or MaxThreads is an ArgumentOutOfRangeException.
A batch is not the fastest way to tokenize many texts: the library puts the results of the texts together on the thread that called it (issue 1559). With 1,024 texts of 1,380 characters on 32 processors, TokenizeBatch tokenized about 2,000 texts a second, and one tokenizer that 16 threads called Tokenize on about 18,000. Threads that share one Tokenizer are the way for many texts.
foreach (SurfaceToken surface in tokenizer.TokenizeSurfaces("関西国際空港限定トートバッグ"))
{
Console.WriteLine($"{surface.Surface} {surface.Start}..{surface.End}");
}
foreach (NBestResult result in tokenizer.TokenizeNBest("すもももももももものうち", 2))
{
Console.WriteLine($"{result.Cost} {string.Join(" / ", result.Tokens.Select(t => t.Surface))}");
}
string[] texts = ["東京都に住む", "関西国際空港"];
IReadOnlyList<IReadOnlyList<Token>> batch = tokenizer.TokenizeBatch(texts, new BatchOptions { MaxThreads = 2 });
for (int i = 0; i < texts.Length; i++)
{
Console.WriteLine($"{texts[i]}: {batch[i].Count} tokens");
}
With IPADIC, the surfaces are 関西国際空港 0..6, 限定 6..8 and トートバッグ 8..14, the best tokenization of すもももももももものうち is すもも / も / もも / も / もも / の / うち, and the batch has 4 tokens and 1 token.
Token
| Property | What it is |
|---|---|
Surface | The surface form: the text of the token, after the filters |
Start, End | The range of the token in the text, as indexes of the .NET string (Offsets) |
ByteStart, ByteEnd | The range of the token in the UTF-8 of the text, as the library gives it |
Position | The position of the token among the tokens, from 0 |
Details | The fields of the word in the dictionary (the part of speech, the reading and so on), made strings when they are first read |
WordId | The ID of the word in the dictionary |
IsUnknown | Whether the word is not in the dictionary |
Dependency | The bunsetsu of the token and what it depends on, or null unless the token filter japanese_dependency wrote it |
SurfaceToken and NBestResult
SurfaceToken is a value with Surface, Start, End, ByteStart and ByteEnd, as a Token has them. NBestResult has the tokens of a tokenization (Tokens) and its cost (Cost): the lower, the better. The tokens of each tokenization keep the bytes of their own details, not those of the others.
Dependency
Dependency is a value that the token filter japanese_dependency writes:
| Property | What it is |
|---|---|
Score | The score of the decision that attached the bunsetsu to its head |
Sentence | The number of the sentence in the text, from 0 |
Bunsetsu | The number of the bunsetsu of the token in its sentence, from 0 |
Head | The number of the bunsetsu that one depends on, or null for the last bunsetsu of a sentence |
Role | What the token is in its bunsetsu: BunsetsuRole.Head, Function, HeadFunction or Other |
LinderaNames.Of(BunsetsuRole role) is the name the library gives a role, such as head.