Quick Start
This guide shows how to tokenize text from a .NET program with Lindera .NET.
Basic Tokenization
The program below is lindera-dotnet/examples/Tokenize/Program.cs. 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.
using Lindera;
if (args.Length < 1)
{
Console.Error.WriteLine("usage: Tokenize <dictionary> [<text>]");
return 2;
}
string dictionary = args[0];
string text = args.Length > 1 ? args[1] : "関西国際空港限定トートバッグ";
try
{
// A builder collects the settings; the tokenizer is built from them.
using TokenizerBuilder builder = new TokenizerBuilder().SetDictionary(dictionary);
using Tokenizer tokenizer = builder.Build();
// The tokens are .NET values: there is nothing to free after them.
foreach (Token token in tokenizer.Tokenize(text))
{
Console.WriteLine($"{token.Surface}\t{string.Join(',', token.Details)}");
}
Console.WriteLine("EOS");
return 0;
}
catch (LinderaException e)
{
Console.Error.WriteLine($"{e.Kind}: {e.Message}");
return 1;
}
Put it in a console project that has the package (see Installation), and run it with the path of a dictionary:
dotnet new console -o Tokenize
cd Tokenize
dotnet add package Lindera
# replace Program.cs with the program above
dotnet run -- /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:
dotnet run -- /path/to/lindera-ipadic 東京都に住む
東京 名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トーキョー
都 名詞,接尾,地域,*,*,*,都,ト,ト
に 助詞,格助詞,一般,*,*,*,に,ニ,ニ
住む 動詞,自立,*,*,五段・マ行,基本形,住む,スム,スム
EOS
What the program does
- It builds a tokenizer. A builder collects the settings (here the dictionary alone), and
Buildmakes the tokenizer, which loads the dictionary. A setter of the builder throws at once when the library refuses a value;Buildthrows when the dictionary cannot be loaded. - It tokenizes.
Tokenizereturns the tokens as a list of .NET values. The result of the library is freed beforeTokenizereturns, so there is nothing to free after the tokens. - It disposes the tokenizer and the builder.
usingcallsDispose, which frees the memory of the library they hold.
A failure of the library is a LinderaException. The program prints its kind and the message of the library:
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 has its place in the text and the fields of its word in the dictionary:
Token token = tokens[0];
Console.WriteLine($"Surface: {token.Surface}");
Console.WriteLine($"Range: {token.Start} {token.End}");
Console.WriteLine($"Byte range: {token.ByteStart} {token.ByteEnd}");
Console.WriteLine($"Position: {token.Position}");
Console.WriteLine($"Unknown: {token.IsUnknown}");
Console.WriteLine($"Details: {token.Details.Count}");
Console.WriteLine($"Part of speech: {token.Details[0]}");
For the first token of 東京都 with IPADIC, this prints:
Surface: 東京
Range: 0 2
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 null without it.
Start and End index the .NET string, whose characters outside the Basic Multilingual Plane take two code units, and ByteStart and ByteEnd are offsets in its UTF-8:
string text = "😀東京";
foreach (Token token in tokenizer.Tokenize(text))
{
Console.WriteLine($"{text[token.Start..token.End]} {token.Start}..{token.End} bytes {token.ByteStart}..{token.ByteEnd}");
}
😀 0..2 bytes 0..4
東京 2..4 bytes 4..10
Filters
Character filters and token filters are appended to the builder, by name, with their arguments as a JSON object, or without arguments:
using TokenizerBuilder builder = new TokenizerBuilder()
.SetDictionary("embedded://ipadic")
.AppendCharacterFilter("unicode_normalize", """{"kind": "nfkc"}""")
.AppendTokenFilter("lowercase");
using Tokenizer tokenizer = builder.Build();
With these two, LINDERA is one token, lindera. (embedded://ipadic names the dictionary a library was built with; with the library of the package it is the path of a directory.)
Threads
One tokenizer serves the threads of a program: their calls of Tokenize run in parallel, and the tokenizer does not have to be made again for each of them:
using TokenizerBuilder builder = new TokenizerBuilder().SetDictionary("embedded://ipadic");
using Tokenizer tokenizer = builder.Build();
Parallel.For(0, texts.Length, i =>
{
counts[i] = tokenizer.Tokenize(texts[i]).Count;
});
See Lindera .NET.