Dictionary Management

The functions and 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 (who closes an object, how an error is returned, what goroutines may do) is in Lindera Go.

Building a dictionary

FunctionWhat it does
BuildDictionary(inputDir, outputDir string, metadata *Metadata, opts ...BuildOption) errorBuilds a dictionary from its source files
WithContextIDFreq(path string)The option of BuildDictionary: the path of a histogram of the context IDs

BuildDictionary 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 LoadMetadata.

WithContextIDFreq 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 fails with an error of the kind KindInvalidArgument when metadata is nil, and of the kind KindIO when the source directory or the histogram cannot be read. The message 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:

source := filepath.Join("..", "resources", "connection_id_mapping")
output, err := os.MkdirTemp("", "lindera")
if err != nil {
	log.Fatal(err)
}
defer os.RemoveAll(output)

// The metadata says how the source files are read: their encoding and
// the fields of their rows.
metadata, err := lindera.LoadMetadata(filepath.Join(source, "metadata.json"))
if err != nil {
	log.Fatal(err)
}
schema, err := metadata.DictionarySchema()
if err != nil {
	log.Fatal(err)
}
fmt.Println(metadata.Name(), metadata.Encoding(), schema.FieldCount())

if err := lindera.BuildDictionary(filepath.Join(source, "source"), output, metadata); err != nil {
	log.Fatal(err)
}

// The directory that was written is a dictionary like any other.
dictionary, err := lindera.LoadDictionary(output)
if err != nil {
	log.Fatal(err)
}
defer dictionary.Close()
tokenizer, err := lindera.NewTokenizer(dictionary)
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, strings.Join(token.Details, ","))
}
fmt.Println("EOS")

Expected output:

connection_id_mapping UTF-8 13
東京    名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トウキョウ
都    名詞,一般,*,*,*,*,*,*,*
EOS

The code is an example of the package (ExampleBuildDictionary in lindera-go/example_test.go), which go test runs from the directory lindera-go and whose output it compares.

Building a user dictionary

FunctionWhat it does
BuildUserDictionaryFor(inputFile, outputFile string, dictionary *Dictionary) errorBuilds a user dictionary from a CSV file for a dictionary, and writes it to a file
BuildUserDictionary(inputFile, outputFile string, metadata *Metadata) errorThe same, with a metadata
LoadUserDictionary(uri string, metadata *Metadata) (*UserDictionary, error)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 functions 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.

FunctionBuilds withThe context IDs of a row
BuildUserDictionaryForThe metadata of dictionaryChecked against the connection matrix of the dictionary as the CSV is built. A row outside the matrix fails the call with an error of the kind KindParse, the message names its line and its surface (line 2 (surface: '東武スカイツリーライン')), and no file is written
BuildUserDictionarymetadata; nil is the default metadataNot 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 fail with an error of the kind KindIO when the CSV cannot be read. The message starts with Failed to build user dictionary:.

LoadUserDictionary loads a user dictionary (a .csv or a .bin file) with a metadata, as LoadUserDictionaryFor loads one for a dictionary. As BuildUserDictionary, it does not check the context IDs of a CSV, and it fails with an error of the kind KindInvalidArgument when metadata is nil. With a dictionary that is loaded, the two functions 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.
bin := filepath.Join(directory, "userdic.bin")
if err := lindera.BuildUserDictionaryFor(csv, bin, dictionary); err != nil {
	log.Fatal(err)
}
userDictionary, err := lindera.LoadUserDictionaryFor(bin, dictionary)
if err != nil {
	log.Fatal(err)
}
defer userDictionary.Close()

Metadata

The metadata of a dictionary: what its metadata.json holds.

Function or methodWhat it does
NewMetadata() (*Metadata, error)Makes a metadata with the default values
LoadMetadata(path string) (*Metadata, error)Reads a metadata from a JSON file, such as the metadata.json of a dictionary
(*Dictionary).Metadata() (*Metadata, error)A copy of the metadata of a dictionary that is loaded

LoadMetadata fails with an error of the kind KindIO when the file cannot be read, and of the kind KindParse 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 closed before it.

A Metadata has no Close: it is freed when it is no longer reachable. It is for one goroutine at a time.

Each value has a method that reads it and one that sets it, Set<Value>, which returns an error:

ValueTypeDefaultWhat it is
NamestringdefaultThe name of the dictionary
EncodingstringUTF-8The character encoding of the source files
DefaultWordCostint16-10000The cost of a simple entry of a user dictionary, which gives none
DefaultLeftContextIDuint161288The left context ID of a simple entry of a user dictionary
DefaultRightContextIDuint161288The right context ID of a simple entry of a user dictionary
DefaultFieldValuestring*The value of the fields a simple entry of a user dictionary lacks
FlexibleCSVboolfalseWhether the rows of the CSV files may have a varying number of columns
SkipInvalidCostOrIDboolfalseWhether a build skips the rows with an invalid cost or context ID, instead of failing
metadata, err := lindera.NewMetadata()
if err != nil {
	log.Fatal(err)
}
fmt.Println(metadata.Name(), metadata.Encoding(), metadata.DefaultWordCost())

if err := metadata.SetName("my-dictionary"); err != nil {
	log.Fatal(err)
}
if err := metadata.SetDefaultWordCost(-5000); err != nil {
	log.Fatal(err)
}
fmt.Println(metadata.Name(), metadata.DefaultWordCost())

// The schema of the user dictionaries: the fields of a simple entry.
schema, err := metadata.UserDictionarySchema()
if err != nil {
	log.Fatal(err)
}
fmt.Println(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:

MethodWhat it does
DictionarySchema() (*Schema, error)A copy of the schema of the dictionary: the fields of the rows of its lexicons
SetDictionarySchema(schema *Schema) errorSets the schema of the dictionary, of which the metadata takes a copy
UserDictionarySchema() (*Schema, error)A copy of the schema of the user dictionaries: the fields of a simple entry (surface, reading and pronunciation by default)
SetUserDictionarySchema(schema *Schema) errorSets the schema of the user dictionaries, of which the metadata takes a copy
SpacePenaltyJSON() stringThe left-space penalty rules the metadata ships, as JSON text

The two methods that set a schema fail with an error of the kind KindInvalidArgument for no schema (nil).

SpacePenaltyJSON returns the rules as JSON text ({"rules":[{"pos":["JKS"],"cost":6000}]}): what SetSpacePenaltyJSON and WithSpacePenaltyJSON take. A metadata without rules, as all but that of ko-dic are, gives an empty string.

A metadata that is read from a file keeps the settings of the file that have no method 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.

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 goroutines may use one at the same time. As a Metadata, it has no Close.

FunctionWhat it does
NewSchema(fields []string) (*Schema, error)Makes a schema from the names of its fields
DefaultSchema() (*Schema, error)Makes the default 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.

MethodReturns
FieldCount() intThe number of fields
Fields() []stringThe names of the fields
CustomFields() []stringThe names of the fields after the first four
FieldName(index int) (string, bool)The name of the field at an index; false for an index the schema does not have
FieldIndex(name string) (int, bool)The index of the field of a name; false when the schema has no such field
Field(name string) (FieldDefinition, bool)The definition of the field of a name; false when the schema has no such field
ValidateRecord(record []string) errorChecks the values of one entry (a row of a CSV) against the schema
schema, err := lindera.NewSchema([]string{"surface", "left_context_id", "right_context_id", "cost", "pos", "reading"})
if err != nil {
	log.Fatal(err)
}
// The fields after the first four are what a token gives as its
// details.
fmt.Println(schema.CustomFields())

index, ok := schema.FieldIndex("reading")
fmt.Println(index, ok)

field, ok := schema.Field("cost")
fmt.Println(field.Index, field.Name, field.Type, ok)

// A row of a CSV is checked against the schema.
err = schema.ValidateRecord([]string{"東京", "1", "2"})
fmt.Println(errors.Is(err, lindera.ErrValidation), err)
[pos reading]
5 true
3 cost cost true
true lindera: validation: CSV row has 3 fields but schema requires 6 fields

ValidateRecord fails with an error of the kind KindValidation 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 struct:

FieldTypeWhat it is
IndexintThe index of the field in its schema, from 0
NamestringThe name of the field
TypeFieldTypeWhat the field holds
DescriptionstringA description of the field. The definitions a schema gives have none

A FieldType is one of these constants, and its String method returns the name:

ConstantNameThe field
FieldTypeSurfacesurfaceThe first: the surface of the word
FieldTypeLeftContextIDleft_context_idThe second: the left context ID
FieldTypeRightContextIDright_context_idThe third: the right context ID
FieldTypeCostcostThe fourth: the cost of the word
FieldTypeCustomcustomEvery field after the fourth