Skip to content

User Dictionary ​

Use a user dictionary when a domain-specific word should be treated as one token or needs an explicit part of speech or base form.

Quick Start ​

Without a dictionary, 生成AI (generative AI) splits into two tokens. One TSV row joins it:

typescript
import { Suzume } from '@libraz/suzume'

const suzume = await Suzume.create()
const show = () => suzume.analyze('生成AIで要約した').map((m) => m.surface).join(' | ')

console.log(show()) // 生成 | AI | で | 要約 | し | た
const count = suzume.loadUserDictionary('生成AI\tNOUN\n')
console.log(count)  // 1
console.log(show()) // 生成AI | で | 要約 | し | た
suzume.destroy()

Try your own rows here. The demo analyzes the same text with and without the dictionary:

Loading WASM...

Source Format ​

The source format is tab-separated text, one entry per line. Every loader and suzume-cli dict compile / dict validate read this one layout:

text
surface<TAB>POS[<TAB>conj_type][<TAB>base_form]
FieldRequiredDescription
surfaceYesText matched by the dictionary
POSYesPart of speech
conj_typeNoConjugation type or proper-name marker
base_formNoBase form; leave conj_type empty when only a base form is needed

This example registers a noun, a verb whose forms are expanded, and a noun with an explicit base form, one per row:

tsv
生成AI	NOUN
もふる	VERB	GODAN_RA
スマホ	NOUN		スマートフォン

Each row changes the analysis of a sentence:

RowSentenceWithout the rowWith the row
生成AI NOUN生成AIで要約した生成 / AI / で / 要約 / し / た生成AI / で / 要約 / し / た
もふる VERB GODAN_RA猫をもふった猫 / を / も / ふっ / た猫 / を / もふっ / た (もふっ has base form もふる)
スマホ NOUN (base form スマートフォン)スマホを買ったスマホ has base form スマホスマホ has base form スマートフォン

Use actual tab characters between fields. Blank lines and lines whose first non-whitespace character is # are ignored.

At runtime and when compiling to .dic, each entry after conjugation expansion can have at most 255 UTF-8 bytes in its surface and at most 255 in its base form. The surface cannot contain a NUL byte (U+0000).

Part-of-speech Values ​

POS is matched exactly, including case: NOUN loads, noun fails with Invalid POS at line N: noun. Each part of speech accepts the names in its row.

Part of speechAccepted names
NounNOUN, PROPN, PROPER_NOUN, 名詞
VerbVERB, 動詞
AdjectiveADJ, ADJECTIVE, 形容詞
AdverbADV, ADVERB, 副詞
ParticlePARTICLE, 助詞
AuxiliaryAUX, AUXILIARY, 助動詞
ConjunctionCONJ, CONJUNCTION, 接続詞
Adnominal adjectiveDET, DETERMINER, ADNOMINAL, 連体詞
PronounPRON, PRONOUN, 代名詞
PrefixPREFIX, 接頭辞
SuffixSUFFIX, 接尾辞
InterjectionINTJ, INTERJECTION, 感動詞
SymbolSYMBOL, SYM, 記号
Other or phraseOTHER, PHRASE, その他

PROPN and PROPER_NOUN create a noun with the proper-noun classification: a ミカヅキ堂 row gives the token ミカヅキ堂 the extended POS NOUN_固有 in ミカヅキ堂へ行く, where a NOUN row gives NOUN. An interjection row takes the interjection conjugation type automatically.

Closed-class entries

PARTICLE and AUX are accepted, but each row produces a warning. Grammatical particles and auxiliaries normally belong in Suzume's built-in layer (L1) rather than a user dictionary.

Conjugation Types ​

Set conj_type to describe conjugation or a more specific grammatical class. Matching verbs and i-adjectives generate inflected entries from the base form.

ValueUse
ICHIDANIchidan verb
GODAN_KA, GODAN_GA, GODAN_SA, GODAN_TAGodan verb in the corresponding row
GODAN_NA, GODAN_BA, GODAN_MA, GODAN_RA, GODAN_WAGodan verb in the corresponding row
SURU, KURUIrregular verb
I_ADJ, NA_ADJI-adjective or na-adjective
INTJInterjection marker
FAMILY, GIVENFamily-name or given-name marker
NONENo conjugation type; the same as an empty field

conj_type is matched exactly, including case. Besides the names above, the PascalCase spellings Ichidan, GodanKa, GodanGa, GodanSa, GodanTa, GodanNa, GodanBa, GodanMa, GodanRa, GodanWa, Suru, Kuru, IAdjective, NaAdjective, Interjection, ProperFamily, ProperGiven, and None are accepted, along with INTERJECTION, PROPER_FAMILY, and PROPER_GIVEN. A verb or i-adjective with a matching marker expands into its inflected forms, and each form becomes its own runtime entry.

One source row expands into its inflected entries
One TSV row expands into 10 entries as GODAN_RA and into 6 entries as ICHIDAN.Correct classloadUserDictionary() → 10もふるVERBGODAN_RAone TSV rowもふるterminalもふりcontinuativeもふらirrealisもふっonbinもふろirrealis before うもふらんirrealis + んもふらぬirrealis + ぬもふれconditionalもふれimperativeもふれるpotentialもふっ in 猫をもふったisUserDict: trueWrong pickloadUserDictionary() → 6もふるVERBICHIDANone TSV rowもふるもふもふんもふれもふよもふろもふっ in 猫をもふったisUserDict: false
Both rows load with no error and no warning. もふれ is installed twice, as the conditional and as the imperative. As ICHIDAN no もふっ entry exists, so the もふっ in 猫をもふった no longer comes from the user dictionary.

The proper-name and na-adjective markers change the label of the token instead of adding forms:

RowSentenceTokenEffect
榊原 NOUN FAMILY榊原さんが来た榊原NOUN_姓 (a NOUN row gives NOUN)
朔也 NOUN GIVEN朔也くんが来た朔也NOUN_名 (a NOUN row gives NOUN)
ゆるふわ ADJ NA_ADJゆるふわな服ゆるふわADJ_NA (an ADJ row without a marker gives ADJ_終止)

NA_ADJ does not expand: one row installs one entry.

A third field that is not a marker is read as the base form. A misspelled or lowercase marker such as suru therefore loads without a warning, as a base form, and no forms are expanded. A numeric third field is an error (see Removed Layouts); a numeric base form goes in the fourth column with the third left empty, as in 一<TAB>NOUN<TAB><TAB>1.

How to pick conj_type

Find the class from the dictionary form. See godan and ichidan for the verb distinction.

EntryPOSconj_typeClass
食べるVERBICHIDANIchidan verb: 食べない, 食べます
書くVERBGODAN_KAGodan verb ending in く: 書かない, 書きます
話すVERBGODAN_SAGodan verb ending in す: 話さない, 話します
点検するVERBSURUNoun + する; see what a SURU row changes
高いADJI_ADJI-adjective: 高くない
静かADJNA_ADJNa-adjective: 静かな

A wrong pick fails silently: the row loads with no error and no warning, but expands into the wrong forms, as the ICHIDAN row in the figure above shows. After loading, analyze a conjugated sentence and check the user-dictionary flag.

Loading WASM...

What a SURU Row Changes ​

Without a row, built-in analysis keeps a suru-verb as a noun followed by する: 点検する gives 点検 (NOUN) / する (VERB), and 点検した gives 点検 / し (VERB, base form する) / た. A 点検する VERB SURU row installs whole-word entries only for some forms. 点検する, 点検すれば, 点検しろ and 点検せよ each become one VERB token with base form 点検する and the user-dictionary flag, while 点検した, 点検します and 点検しない split as 点検 / し / ….

Removed Layouts ​

Rows in the older layouts are not converted or ignored. Each of these fails the whole load as a parse error, in every loader and in suzume-cli dict compile / dict validate. N is the line number:

Row shapeError text
Comma-delimited rows, for example 生成AI,NOUN,5000Removed legacy CSV layout at line N; use tab-separated rows
Numeric third column, for example 生成AI<TAB>NOUN<TAB>5000Removed cost column at line N: column 3 is numeric; rows are surface, POS[, conj_type][, base_form]
Four or more columns with a numeric fourth column after a non-empty third column that is not a conjugation typeRemoved legacy TSV layout at line N: column 4 is a numeric cost; rows are surface, POS[, conj_type][, base_form]

A malformed quoted field fails with Invalid quoting at line N: <detail>, where the detail is unterminated quoted field or unexpected character after closing quote. A row with a non-empty third column that is not a conjugation type and a non-empty fourth column fails with Ambiguous non-empty TSV columns 3 and 4 at line N.

Runtime Loading ​

Each successful call adds another source or binary dictionary to the same instance. The CLIs apply each repeatable --dictionary (-d) argument to the instance used by that command.

typescript
import { Suzume, SuzumeError } from '@libraz/suzume'

const suzume = await Suzume.create()
const source = '生成AI\tNOUN\nもふる\tVERB\tGODAN_RA\n'

try {
  const expandedCount = suzume.loadUserDictionary(source)
  console.log(expandedCount)
} catch (error) {
  if (error instanceof SuzumeError) {
    console.error(error.message)
  }
  throw error
} finally {
  suzume.destroy()
}
python
from suzume import Suzume, SuzumeError

source = "生成AI\tNOUN\nもふる\tVERB\tGODAN_RA\n"

with Suzume() as suzume:
    try:
        expanded_count = suzume.load_user_dictionary(source)
    except SuzumeError as error:
        print(error)
        raise
go
package main

import (
	"fmt"
	"log"

	"github.com/libraz/go-suzume"
)

func main() {
	analyzer, err := suzume.New()
	if err != nil {
		log.Fatal(err)
	}
	defer analyzer.Close()

	source := []byte("生成AI\tNOUN\nもふる\tVERB\tGODAN_RA\n")
	expandedCount, err := analyzer.LoadUserDictionary(source)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(expandedCount)
}
cpp
#include "suzume/suzume.hpp"

#include <iostream>

int main() {
  auto tokenizer = suzume::Tokenizer::create();
  if (!tokenizer) {
    std::cerr << tokenizer.error().message << "\n";
    return 1;
  }
  const auto expanded_count =
      tokenizer->loadUserDictionary("生成AI\tNOUN\nもふる\tVERB\tGODAN_RA\n");
  if (!expanded_count) {
    std::cerr << expanded_count.error().message << "\n";
    return 1;
  }
  std::cout << *expanded_count << "\n";
  return 0;
}
c
#include "suzume/suzume_c.h"

#include <stdio.h>
#include <string.h>

int main(void) {
  suzume_t tokenizer = suzume_create();
  if (!tokenizer) {
    fprintf(stderr, "%s\n", suzume_last_error());
    return 1;
  }
  const char* source = "生成AI\tNOUN\nもふる\tVERB\tGODAN_RA\n";
  const size_t expanded_count =
      suzume_load_user_dictionary(tokenizer, source, strlen(source));
  if (expanded_count == 0) {
    fprintf(stderr, "%s\n", suzume_last_error());
    suzume_destroy(tokenizer);
    return 1;
  }
  printf("%zu\n", expanded_count);
  suzume_destroy(tokenizer);
  return 0;
}
bash
# user.tsv contains the same tab-separated rows.
# -d / --dictionary is repeatable and also accepts compiled .dic files.
suzume --dictionary user.tsv "生成AIで要約した"                 # Python wheel
suzume-cli analyze --dictionary user.tsv "生成AIで要約した"     # native CLI

Return Values and Errors ​

BindingSource dictionary resultFailure details
JavaScriptloadUserDictionary() returns the installed-entry countThrows SuzumeError (code, operation, message)
Pythonload_user_dictionary() returns the installed-entry countRaises SuzumeError
GoLoadUserDictionary() returns (int, error)*suzume.Error with Code, Op, and Message
C++loadUserDictionary() returns Expected<std::size_t>error() on the result carries code, message, and operation
C ABIsuzume_load_user_dictionary() returns the installed-entry countA return of 0 is a failure; read suzume_last_error() / suzume_last_error_code()
CLIExits with status 1 when a dictionary cannot be loadedPrints <prog>: error: failed to load dictionary: <path>: <native text> to standard error

The binary loaders (loadBinaryDictionary() and its equivalents) return the installed-entry count the same way. Failure is an exception or an error value in every binding except the C ABI, which returns 0. A successful source load always installs at least one entry. The count is measured after conjugation expansion and duplicate removal, not by counting source rows.

message is the native text unchanged. A malformed source is a parse error (code 4), and an empty source fails with Empty dictionary data (code 6, invalid input). Loading 生成AI,NOUN,5000 gives:

text
Removed legacy CSV layout at line 1; use tab-separated rows

The JavaScript and Python loaders take the source as text or as its UTF-8 bytes: a Uint8Array in JavaScript, and bytes, bytearray or memoryview in Python. Bytes that are not valid UTF-8 fail with Dictionary entry is not valid UTF-8 at line N (code 4). Any other argument type is rejected with invalid dictionary: <value> (expected a string or binary data): a SuzumeError with code 6 in JavaScript, a ValueError in Python.

A failed source or binary load does not remove or replace dictionaries already installed on the instance. It also does not install the valid prefix of a source file. Successful loads remain additive until they are cleared or the instance is destroyed.

Warnings and Partially Valid Input ​

A load parses the whole source, then installs entry by entry
Flow of a user dictionary source load. A parse error fails the load and installs nothing; short rows and rejected entries are skipped with a warning; zero installed entries fails the load, otherwise the count is returned.Parse the whole sourceall rows, before installingShort rowsfewer than two fieldsExpand valid rowsconjugation expansionInstall each entrye.g. surface over 255 bytesAny entry installed?counted after expansion≥ 1errorLoad fails, nothing installedremoved layout, bad quoting, invalid UTF-8, bad POSshort rowRow skipped, warning recordedSkipped dictionary record at line N: missing POS fieldrejectedEntry skipped, warning recordedSkipped N invalid dictionary entriesnoneLoad failsDictionary source contains no loadable entriesReturns the installed countsee dictionaryWarningsEarlier dictionaries untouchedon success and on failure
A failed load installs nothing, not even the valid prefix. Warnings survive only when at least one entry installs; if every row is skipped or every entry rejected, the load itself fails. Both cases report the same message.

Runtime source loading skips a record with fewer than two fields. If another row is valid, the valid rows are installed and the skipped row is recorded as a warning:

text
missing-pos
生成AI	NOUN

If at least one entry installs, the runtime loader skips any expanded entries that fail the field checks and records Skipped N invalid dictionary entries. To check a source file before loading it, run suzume-cli dict validate. Both dict validate and dict compile report the affected source lines and exit with status 1 when an expanded entry fails these checks.

Warnings from runtime loads are appended to the instance's dictionary-warning list:

BindingRead warnings
JavaScriptdictionaryWarnings
Pythondictionary_warnings
GoDictionaryWarnings()
C++Tokenizer::dictionaryWarnings()
C ABIsuzume_dictionary_warning_count() and suzume_dictionary_warning()
CLIsPrinted to standard error as warning: <text> after each -d / --dictionary load

clearUserDictionaries() and its equivalents clear runtime-load warnings but retain construction-time warnings.

If parsing succeeds but no entries can be installed, the load fails with Dictionary source contains no loadable entries (code 4). Unknown POS values, empty required fields, invalid UTF-8, malformed quoting, the removed layouts, and non-empty columns after the fourth cause the entire source load to fail during parsing.

Dictionary Layers ​

Clearing removes only what the caller loaded
The four dictionary layers, and which of them the creation-time skip options and clearUserDictionaries() affect.LayerSkip at creationclearUserDictionaries()L1Built-inparticles, auxiliaries, formal nouns; compiled in—keptL2Core dictionarygeneral vocabulary · core.dicskipCoreDictionarykeptL3Bundled user dictionarysupplementary vocabulary · user.dicskipBundledUserDictionarykeptL4Caller-loaded dictionariesloadUserDictionary · loadBinaryDictionary—removedEvery layer adds candidates to the same lattice; scoring picks the path.
Only the L4 row changes on clear. L2 and L3 can be left out only when the instance is created.

The layers are numbered L1 to L4, and other pages use these names:

LayerHoldsComes from
L1Built-in grammar inventory: particles, auxiliaries, conjunctions, determiners, pronouns, formal nouns, interjectionsCompiled into the library
L2Core vocabularycore.dic
L3Bundled user dictionaryuser.dic
L4Caller-loaded dictionariesRuntime loading calls

All four layers are consulted at every position, and no layer hides another layer's entries. L1 is always present, core.dic and user.dic load automatically when the instance is created, and L4 stays until it is cleared or the instance is destroyed. Entries from L3 and L4 receive a score bonus, which is why a user-dictionary row usually wins over the split it replaces. It does not always win: see When a Row Does Not Win.

Tokens from both user-dictionary layers report the user-dictionary flag. The npm package, the PyPI wheel, and the Go binding embed or ship core.dic and user.dic, so no setup is needed.

Where core.dic and user.dic are read from depends on the binding:

BindingSource of core.dic and user.dic
JavaScriptEmbedded in the WASM module only. There is no data-directory option and no environment variable
PythonThe wheel's bundled data directory only. SUZUME_DATA_DIR and ~/.suzume are not consulted, and there is no data_directory argument
GoOptions.DataDirectory when set. With default options, Go passes the embedded copies staged at startup. If SUZUME_DATA_DIR is set at instance creation or the embedded files could not be staged, the core uses its native search order. See the Go guide
C++ and Cdata_directory when set, exclusively; otherwise the first directory that holds each file among SUZUME_DATA_DIR, ~/.suzume, the install data directory, /usr/local/share/suzume, /usr/share/suzume and ./data. A build configured with SUZUME_EMBED_DICT=ON embeds both files and reads no path or variable
Native CLIThe same search as C++, without a data-directory flag; see Environment Variables

The skip options apply only when an instance is created. Clearing removes every source and binary dictionary loaded on that instance and leaves the other three layers in place:

BindingSkip core.dicSkip bundled user.dicClear caller-loaded dictionaries
JavaScriptskipCoreDictionary: trueskipBundledUserDictionary: trueclearUserDictionaries()
Pythonskip_core_dictionary=Trueskip_bundled_user_dictionary=Trueclear_user_dictionaries()
GoOptions.SkipCoreDictionaryOptions.SkipBundledUserDictionaryClearUserDictionaries(), which returns error
C++Options::skip_core_dictionaryOptions::skip_bundled_user_dictionaryclearUserDictionaries(), which returns Expected<void>
C ABIskip_core_dictionary in suzume_options_tskip_bundled_user_dictionary in suzume_options_tsuzume_clear_user_dictionaries(handle)
CLI--skip-core-dictionary--skip-bundled-user-dictionaryNot needed; dictionaries last for one invocation

--skip-bundled-user-dictionary skips only the bundled user.dic; files passed with --dictionary still load.

Verifying a Match ​

A token reports whether it came from a user dictionary, including the bundled one:

BindingFlag
JavaScriptisUserDict
Pythonis_user_dict
GoIsUserDict
C++is_user_dict
C ABISUZUME_MORPHEME_USER_DICT flag

Splitting a Compound ​

An unmatched run of kanji such as 東京都庁前 stays one token in every mode. Registering its parts splits it:

tsv
東京	NOUN
都庁	NOUN
前	NOUN
InputWithout the rowsWith the rows
東京都庁前東京都庁前東京 / 都庁 / 前
東京都庁前を歩く東京都庁前 / を / 歩く東京 / 都庁 / 前 / を / 歩く

In search mode, or with mergeCompounds, the three nouns merge back into 東京都庁前.

When a Row Does Not Win ​

A row wins when the path through it has a lower total cost than every competing path. It loses when another path costs less. A row for 都庁 alone leaves 東京都庁前 whole, because the single token that covers the whole run costs less than a path through 東京 + 都庁 + 前. To find out why, check these in order:

  1. Read the user-dictionary flag on the tokens. If no token has it, the row did not take part in the chosen path.
  2. With the native CLI, suzume-cli analyze --compare -d rows.tsv "東京都庁前" prints the analysis without the rows, with them, and the difference. No structural difference means the rows changed nothing.
  3. suzume-cli analyze --debug -d rows.tsv "東京都庁前" writes the lattice candidates to standard error, with their costs and a [dict:user] mark on user-dictionary candidates, and the best path.
  4. Register the neighbouring pieces too, as in the table above, or a longer entry that spans the boundary you need: a single 都庁前 row gives 東京 / 都庁前.
  5. Lower unary.user_dict_bonus (default -2.0) through scorerOptions. With -4 a lone 都庁 row splits 東京都庁前. The change applies to every user-dictionary entry.

--compare and --debug exist in the native CLI only.

Binary Dictionaries ​

Compile source TSV when startup time matters or when the same dictionary will be loaded repeatedly. Compiling needs the native suzume-cli, which the npm package and the PyPI wheel do not include.

bash
suzume-cli dict compile user.tsv   # writes user.dic
Compile once, then load the bytes from any binding
user.tsv is compiled by suzume-cli dict compile into a format-version-4 user.dic, which each binding loads. A load that passes the header check is added to the existing dictionaries; one that fails changes nothing.Build timeuser.tsvkeep it as the sourcesuzume-cli dict compilenative CLI onlyuser.dicformat version 4Runtimepass the bytesJS · C++loadBinaryDictionary()Pythonload_binary_dictionary()GoLoadBinaryDictionary()CLI--dictionary user.dicHeader checkmagic · version 4Addedalongside existing onesRejectedexisting ones untouched
A load that fails the check leaves every dictionary loaded before it in place. A .dic of another format version is rejected, so keep the TSV and recompile it with the current CLI.

The C ABI loads the same bytes with suzume_load_binary_dictionary(), which returns the installed-entry count. See dict in the Native CLI reference for the compiler and the file layout.

Persistence ​

Caller-loaded dictionaries live in the instance and disappear when it is destroyed. Store the TSV source or compiled .dic in your application, then load it into each new instance.

  1. Use canonical TSV with literal tab characters.
  2. Add only words whose current tokenization or part of speech needs an override.
  3. Supply conj_type for verbs and adjectives that need inflected forms.
  4. Check the expanded-entry count or binding-specific error after each load.
  5. Analyze a representative sentence and inspect the user-dictionary flag.

See Also ​