Dictionary Management
The types of the package Lindera for the dictionaries themselves: building a dictionary and a user dictionary, the metadata of a dictionary, and its schema. Loading a dictionary for a tokenizer is in Tokenizer API. What the types share (lifetimes, errors and threads) is in Lindera .NET.
Building a dictionary
| Member | What it does |
|---|---|
DictionaryBuilder.Build(string inputDir, string outputDir, Metadata metadata, BuildOptions? options = null) | Builds a dictionary from its source files |
BuildOptions.ContextIdFreqFile | The path of a histogram of the context IDs; none by default |
DictionaryBuilder.Build builds a dictionary from its source files, as lindera dictionary build does. inputDir is the directory of the source files (the lexicons as CSV, matrix.def, char.def, unk.def), and outputDir the directory the dictionary is written to, which is made if it is not there. metadata says how the source files are read. It is normally read from the metadata.json of the dictionary, with Metadata.Load.
ContextIdFreqFile gives the build a histogram of the context IDs, such as the context_id_freq.txt of a dictionary crate. It is read only when the metadata turns connection_id_mapping on, as the metadata.json of ko-dic and of UniDic does. The build then relabels the context IDs of the connection matrix by how often they are read: by the counts of the histogram or, without one, by the count of the entries. The relabelling changes the speed of tokenizing, never its result.
The call throws LinderaException of the kind IO when the source directory or the histogram cannot be read, with a message that starts with Failed to build dictionary:.
The example below reads a metadata, builds a dictionary, loads it, and tokenizes a text with it. The repository has the source of a small dictionary, with one entry (東京), for its tests, in resources/connection_id_mapping:
// The metadata says how the source files are read: their
// encoding and the fields of their rows.
using Metadata metadata = Metadata.Load(Path.Combine(source, "metadata.json"));
using (Schema schema = metadata.GetDictionarySchema())
{
Console.WriteLine($"{metadata.Name} {metadata.Encoding} {schema.FieldCount}");
}
DictionaryBuilder.Build(Path.Combine(source, "source"), output, metadata);
// The directory that was written is a dictionary like any other.
using Dictionary dictionary = Dictionary.Load(output);
using Tokenizer tokenizer = Tokenizer.Create(dictionary);
foreach (Token token in tokenizer.Tokenize("東京都"))
{
Console.WriteLine($"{token.Surface}\t{string.Join(',', token.Details)}");
}
Console.WriteLine("EOS");
Expected output:
connection_id_mapping UTF-8 13
東京 名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トウキョウ
都 名詞,一般,*,*,*,*,*,*,*
EOS
Building a user dictionary
| Member | What it does |
|---|---|
DictionaryBuilder.BuildUserDictionaryFor(string inputFile, string outputFile, Dictionary dictionary) | Builds a user dictionary from a CSV file for a dictionary, and writes it to a file |
DictionaryBuilder.BuildUserDictionary(string inputFile, string outputFile, Metadata metadata) | The same, with a metadata |
UserDictionary.Load(string uri, Metadata metadata) | Loads a user dictionary with a metadata |
BuildUserDictionaryFor and BuildUserDictionary build a user dictionary from the CSV file inputFile and write it to outputFile. The methods that load a user dictionary choose how to read a file by its extension, so outputFile should end with .bin. Its directory is made if it is not there.
| Method | Builds with | The context IDs of a row |
|---|---|---|
BuildUserDictionaryFor | The metadata of dictionary | Checked against the connection matrix of the dictionary as the CSV is built. A row outside the matrix throws LinderaException of the kind Parse, whose message names its line and its surface (line 2 (surface: '東武スカイツリーライン')), and no file is written |
BuildUserDictionary | metadata | Not checked here. A tokenizer checks them when it is made with the user dictionary, and names an entry outside the matrix by its word ID |
Both throw LinderaException of the kind IO when the CSV cannot be read, with a message that starts with Failed to build user dictionary:.
UserDictionary.Load loads a user dictionary (a .csv or a .bin file) with a metadata, as UserDictionary.LoadFor loads one for a dictionary. As BuildUserDictionary, it does not check the context IDs of a CSV. With a dictionary that is loaded, the two methods that end in For are the ones to use:
// The file that is written ends with .bin: a user dictionary is
// loaded by what its name ends with.
string bin = Path.Combine(directory, "userdic.bin");
DictionaryBuilder.BuildUserDictionaryFor(csv, bin, dictionary);
using UserDictionary userDictionary = UserDictionary.LoadFor(bin, dictionary);
Metadata
The metadata of a dictionary: what its metadata.json holds.
| Member | What it does |
|---|---|
new Metadata() | Makes a metadata with the default values |
static Metadata Load(string path) | Reads a metadata from a JSON file, such as the metadata.json of a dictionary |
Dictionary.GetMetadata() | A copy of the metadata of a dictionary that is loaded |
Dispose() | Frees the metadata |
Metadata.Load throws LinderaException of the kind IO when the file cannot be read, and of the kind Parse when it is not the JSON of a metadata. The metadata of a dictionary is a copy: the dictionary does not need it, and can be disposed before it.
Each value is a property that can be read and set:
| Property | Type | Default | What it is |
|---|---|---|---|
Name | string | default | The name of the dictionary |
Encoding | string | UTF-8 | The character encoding of the source files |
DefaultWordCost | short | -10000 | The cost of a simple entry of a user dictionary, which gives none |
DefaultLeftContextId | ushort | 1288 | The left context ID of a simple entry of a user dictionary |
DefaultRightContextId | ushort | 1288 | The right context ID of a simple entry of a user dictionary |
DefaultFieldValue | string | * | The value of the fields a simple entry of a user dictionary lacks |
FlexibleCsv | bool | false | Whether the rows of the CSV files may have a varying number of columns |
SkipInvalidCostOrId | bool | false | Whether a build skips the rows with an invalid cost or context ID, instead of failing |
using var metadata = new Metadata();
Console.WriteLine($"{metadata.Name} {metadata.Encoding} {metadata.DefaultWordCost}");
metadata.Name = "my-dictionary";
metadata.DefaultWordCost = -5000;
Console.WriteLine($"{metadata.Name} {metadata.DefaultWordCost}");
// The schema of the user dictionaries: the fields of a simple entry.
using Schema schema = metadata.GetUserDictionarySchema();
Console.WriteLine(string.Join(' ', schema.Fields));
default UTF-8 -10000
my-dictionary -5000
surface reading pronunciation
The two schemas of a metadata, and the left-space penalty rules it ships:
| Member | What it does |
|---|---|
GetDictionarySchema() | A copy of the schema of the dictionary: the fields of the rows of its lexicons |
SetDictionarySchema(Schema schema) | Sets the schema of the dictionary, of which the metadata takes a copy |
GetUserDictionarySchema() | A copy of the schema of the user dictionaries: the fields of a simple entry (surface, reading and pronunciation by default) |
SetUserDictionarySchema(Schema schema) | Sets the schema of the user dictionaries, of which the metadata takes a copy |
SpacePenaltyJson | The left-space penalty rules the metadata ships, as JSON text, or null |
A schema that is read is a new Schema, which the caller disposes; the metadata keeps its own copy, so a schema that was set can be disposed at once.
SpacePenaltyJson is the rules as JSON text ({"rules":[{"pos":["JKS"],"cost":6000}]}): what SetSpacePenaltyJson and TokenizerOptions.SpacePenaltyJson take. It is null for a metadata without rules, as all but that of ko-dic are.
A metadata that is read from a file keeps the settings of the file that have no property here: the left-space penalty rules, connection_id_mapping, and the formats of the source files. A dictionary built with it is built as lindera dictionary build builds it.
Threads may share a metadata: its calls take turns, and a call that builds or loads with it waits for one that sets a value.
Schema
The schema of a dictionary: the names of the fields of its entries, in the order of the columns of its CSV. A schema does not change once it is made, and threads may use one at the same time.
| Member | What it does |
|---|---|
new Schema(IEnumerable<string> fields) | Makes a schema from the names of its fields, of which it takes a copy |
static Schema CreateDefault() | Makes the default schema |
Dispose() | Frees the schema |
The default schema has 13 fields: surface, left_context_id, right_context_id, cost, major_pos, pos_detail_1, pos_detail_2, pos_detail_3, conjugation_type, conjugation_form, base_form, reading and pronunciation.
The first four fields of a schema are the surface, the left context ID, the right context ID and the cost, whatever their names. The fields after them are the dictionary's own, the custom fields: they are what a token gives as its details.
| Member | Returns |
|---|---|
FieldCount | The number of fields |
Fields | The names of the fields |
CustomFields | The names of the fields after the first four |
NameAt(int index) | The name of the field at an index, or null for an index the schema does not have |
IndexOf(string name) | The index of the field of a name, or null when the schema has no such field |
Field(string name) | The definition of the field of a name (FieldDefinition), or null when the schema has no such field |
ValidateRecord(IReadOnlyList<string> record) | Checks the values of one entry (a row of a CSV) against the schema |
using var schema = new Schema(["surface", "left_context_id", "right_context_id", "cost", "pos", "reading"]);
// The fields after the first four are what a token gives as its
// details.
Console.WriteLine(string.Join(' ', schema.CustomFields));
Console.WriteLine(schema.IndexOf("reading"));
if (schema.Field("cost") is FieldDefinition field)
{
Console.WriteLine($"{field.Index} {field.Name} {field.Type} {LinderaNames.Of(field.Type)}");
}
// A row of a CSV is checked against the schema.
try
{
schema.ValidateRecord(["東京", "1", "2"]);
}
catch (LinderaException e)
{
Console.WriteLine($"{e.Kind}: {e.Message}");
}
pos reading
5
3 cost Cost cost
Validation: CSV row has 3 fields but schema requires 6 fields
ValidateRecord throws LinderaException of the kind Validation when the record has fewer values than the schema has fields, or when a value of a field of the schema is empty (Field reading is missing or empty). The context IDs and the cost may not be blank either. Values after the fields of the schema are not checked.
FieldDefinition and FieldType
FieldDefinition is the definition of one field of a schema, a value:
| Property | Type | What it is |
|---|---|---|
Index | int | The index of the field in its schema, from 0 |
Name | string | The name of the field |
Type | FieldType | What the field holds |
Description | string? | A description of the field. The definitions a schema gives have none (null) |
FieldType is one of these values, and LinderaNames.Of(FieldType) returns the name the library gives it:
| Value | Name | The field |
|---|---|---|
FieldType.Surface | surface | The first: the surface of the word |
FieldType.LeftContextId | left_context_id | The second: the left context ID |
FieldType.RightContextId | right_context_id | The third: the right context ID |
FieldType.Cost | cost | The fourth: the cost of the word |
FieldType.Custom | custom | Every field after the fourth |