Class MecabDictionary
*.csv files, connection costs from matrix.def, character
categories from char.def, and unknown-word templates from unk.def,
loaded from a user-supplied dictionary directory. No dictionary data is bundled or
downloaded by this class.
The same format serves multiple languages: the Japanese IPADIC and UniDic distributions and the Korean mecab-ko-dic all load through this one reader, with the feature columns passed through untouched because their schemas differ.
Each instance uses about 0.75 MB for category tables indexed by the 16-bit
code-unit space, so load once and share. Lexicon CSV files under the directory are
read in sorted path order so tie-breaking is stable across file systems. Connection
costs must cover all matrix cells; missing and duplicate entries are
rejected instead of being treated as cost zero. Matrix dimensions and the lexicon
entry count are bounded by ResourceLimits.MAX_ENTRIES, and the matrix cell
count by ResourceLimits.MAX_MATRIX_CELLS. Lexicon CSV fields may be
MeCab-quoted with "" escapes. Word and connection costs must fit in a signed
16-bit integer. An unk.def template must name a category defined by
char.def.
Instances are immutable and safe to share between threads.
- Since:
- 3.0.0
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static final recordOne character category's unknown-word behavior fromchar.def.(package private) static interfaceReceives one common-prefix match duringprefixMatches(java.lang.String, int, int, opennlp.tools.tokenize.lattice.MecabDictionary.PrefixMatchConsumer).(package private) static final recordOne lexicon or unknown-word entry. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final CategoryTable(package private) static final String(package private) static final Stringprivate final short[](package private) static final StringThe category name everychar.defmust define; unmapped code points and unknown-word handling fall back to it.private final CategoryTable.CategoryAssignment(package private) static final Stringprivate static final StringThechar.deffield value that turns a category flag off.private static final StringThechar.deffield value that turns a category flag on.private static final StringThe code point prefix used bychar.def, in either letter case.private final DoubleArrayLexicon(package private) static final Stringprivate static final String(package private) static final Stringprivate static final intMaximum category count accepted by MeCab's character-property compiler.private static final intMaximum value of MeCab's 4-bit category length field.private static final StringThe separator between the two ends of achar.defcode point range.private final int(package private) static final Stringprivate final Map<String, List<MecabDictionary.WordEntry>> -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateMecabDictionary(DoubleArrayLexicon lexicon, short[] connectionCosts, int rightSize, Map<String, MecabDictionary.Category> categories, CategoryTable categoryTable, Map<String, List<MecabDictionary.WordEntry>> unknownEntries) Creates an immutable dictionary from parsed lexicon and definition data. -
Method Summary
Modifier and TypeMethodDescription(package private) CategoryTable.CategoryAssignmentcategoriesOf(int codePoint) Classifies a character into all categories assigned bychar.def.(package private) MecabDictionary.CategorycategoryOf(int codePoint) Classifies a character by code point, so a character outside the Basic Multilingual Plane is classified once, not as separate surrogate code units.(package private) intconnectionCost(int rightId, int leftId) Reads the connection cost between two adjacent nodes.private static booleanReports whether achar.defcategory flag field is exactly0or1.static MecabDictionaryLoads a dictionary directory encoded in UTF-8.static MecabDictionaryLoads a dictionary directory.private static InvalidFormatExceptionmalformedEntry(Path file, int lineNumber, String detail) Creates the exception for a lexicon line that cannot be read.private static intparseCodePoint(String text, Path file, int lineNumber) Parses a0x-prefixed hexadecimal code point fromchar.def.private static intParses a decimal integer field, reporting the file and line on failure.(package private) voidprefixMatches(String text, int from, int to, MecabDictionary.PrefixMatchConsumer consumer) Reports every lexicon surface starting at a text position, walking the trie once with no substring allocation.private static voidreadCharacterDefinition(Path file, Charset charset, Map<String, MecabDictionary.Category> categories, CategoryTable.Builder categoryTable) Readschar.def: the category behavior lines and the code point mapping lines, in file order, so that a later mapping wins over an earlier one.private static voidreadLexicon(Path file, Charset charset, Map<String, List<MecabDictionary.WordEntry>> target, int leftSize, int rightSize, int[] entryCount) Parses one lexicon-format CSV file, rejecting entries with context ids the connection matrix cannot be indexed with.private static voidrequireFile(Path file) Checks that a required dictionary file exists.Splits a lexicon line on commas, honoring MeCab-style"..."quoting with""escapes inside a quoted field.(package private) List<MecabDictionary.WordEntry> unknownEntries(String category) Looks up the unknown-word templates of a category.
-
Field Details
-
DEFAULT_CATEGORY
The category name everychar.defmust define; unmapped code points and unknown-word handling fall back to it.- See Also:
-
MATRIX_DEF
- See Also:
-
CHAR_DEF
- See Also:
-
UNK_DEF
- See Also:
-
MAX_CATEGORY_COUNT
private static final int MAX_CATEGORY_COUNTMaximum category count accepted by MeCab's character-property compiler.CategoryTable.CategoryAssignmentrelies on this limit staying below 32 for itsintcategory mask.- See Also:
-
MAX_CATEGORY_LENGTH
private static final int MAX_CATEGORY_LENGTHMaximum value of MeCab's 4-bit category length field.- See Also:
-
LEXICON_EXTENSION
- See Also:
-
DEFINITION_EXTENSION
- See Also:
-
CONFIGURATION_FILE
- See Also:
-
LEXICON_GLOB
- See Also:
-
HEX_PREFIX
The code point prefix used bychar.def, in either letter case.- See Also:
-
RANGE_SEPARATOR
The separator between the two ends of achar.defcode point range.- See Also:
-
FLAG_ON
Thechar.deffield value that turns a category flag on.- See Also:
-
FLAG_OFF
Thechar.deffield value that turns a category flag off.- See Also:
-
lexicon
-
connectionCosts
private final short[] connectionCosts -
rightSize
private final int rightSize -
categoryTable
-
defaultCategories
-
unknownEntries
-
-
Constructor Details
-
MecabDictionary
private MecabDictionary(DoubleArrayLexicon lexicon, short[] connectionCosts, int rightSize, Map<String, MecabDictionary.Category> categories, CategoryTable categoryTable, Map<String, List<MecabDictionary.WordEntry>> unknownEntries) Creates an immutable dictionary from parsed lexicon and definition data.- Parameters:
lexicon- The surface lexicon.connectionCosts- The flattened connection matrix.rightSize- The number of left-context columns in each matrix record.categories- The character categories by name.categoryTable- The code point category assignments.unknownEntries- The unknown-word templates by category.
-
-
Method Details
-
load
Loads a dictionary directory encoded in UTF-8.- Parameters:
directory- The unpacked dictionary directory. Must not benull.- Returns:
- The loaded dictionary. Never
null. - Throws:
InvalidFormatException- Thrown if a file is malformed.IOException- Thrown if reading fails, a required file is missing, or a size limit is exceeded.IllegalArgumentException- Thrown ifdirectoryisnull.
-
load
Loads a dictionary directory.- Parameters:
directory- The unpacked dictionary directory holding the*.csvlexicon files,matrix.def,char.def, andunk.def. Must not benull.charset- The encoding the distribution uses, for example UTF-8 or EUC-JP. Must not benull.- Returns:
- The loaded dictionary. Never
null. - Throws:
InvalidFormatException- Thrown if a file is malformed or a lexicon entry's context ids are outside thematrix.defdimensions.IOException- Thrown if reading fails, a required file is missing, or a size limit is exceeded.IllegalArgumentException- Thrown if a parameter isnull.
-
readLexicon
private static void readLexicon(Path file, Charset charset, Map<String, List<MecabDictionary.WordEntry>> target, int leftSize, int rightSize, int[] entryCount) throws IOExceptionParses one lexicon-format CSV file, rejecting entries with context ids the connection matrix cannot be indexed with.- Parameters:
file- The file to read.charset- The encoding to decode with.target- Receives the entries, keyed by surface form.leftSize- The firstmatrix.defdimension, which bounds right context ids.rightSize- The secondmatrix.defdimension, which bounds left context ids.entryCount- A one-element running total of entries read so far, shared across the lexicon files of one load.- Throws:
InvalidFormatException- Thrown if an entry is malformed, has an empty surface, a context id outside the matrix dimensions or a cost outside the 16-bit range.IOException- Thrown if the file is missing, reading fails, or the running entry count exceedsResourceLimits.MAX_ENTRIES.
-
readCharacterDefinition
private static void readCharacterDefinition(Path file, Charset charset, Map<String, MecabDictionary.Category> categories, CategoryTable.Builder categoryTable) throws IOExceptionReadschar.def: the category behavior lines and the code point mapping lines, in file order, so that a later mapping wins over an earlier one.- Parameters:
file- The file to read.charset- The encoding to decode with.categories- Receives the defined categories, keyed by name.categoryTable- Receives the code point to category name mappings.- Throws:
InvalidFormatException- Thrown if a line is malformed, a code point is outside the Unicode range, a range descends, a category is duplicated, category count or length exceeds the MeCab format, or the file defines noDEFAULTcategory.IOException- Thrown if the file is missing or reading fails.
-
prefixMatches
Reports every lexicon surface starting at a text position, walking the trie once with no substring allocation.- Parameters:
text- The text being segmented.from- The position surfaces must start at.to- The exclusive end of the searchable stretch.consumer- Receives each match.
-
connectionCost
int connectionCost(int rightId, int leftId) Reads the connection cost between two adjacent nodes.- Parameters:
rightId- The right context id of the earlier node.leftId- The left context id of the later node.- Returns:
- The connection cost.
-
categoryOf
Classifies a character by code point, so a character outside the Basic Multilingual Plane is classified once, not as separate surrogate code units.- Parameters:
codePoint- The code point to classify.- Returns:
- Its category, falling back to
DEFAULTwhen nochar.defmapping covers the code point. Nevernull.
-
categoriesOf
Classifies a character into all categories assigned bychar.def. The first category supplies unknown-word behavior and all categories participate in run grouping.- Parameters:
codePoint- The code point to classify.- Returns:
- The category assignment, falling back to
DEFAULTwhen no mapping covers the code point.
-
unknownEntries
Looks up the unknown-word templates of a category.- Parameters:
category- The category name.- Returns:
- The templates, or
nullwhen the category has none.
-
isFlag
Reports whether achar.defcategory flag field is exactly0or1.- Parameters:
field- The flag field text.- Returns:
truewhen the field is a recognized flag value.
-
requireFile
Checks that a required dictionary file exists.- Parameters:
file- The file to check.- Throws:
IOException- Thrown iffiledoes not exist.
-
malformedEntry
Creates the exception for a lexicon line that cannot be read.- Parameters:
file- The file the line came from.lineNumber- The line's position in the file.detail- What is wrong with the line, ornullfor no detail.- Returns:
- The exception to throw. Never
null.
-
splitCsv
private static List<String> splitCsv(String line, Path file, int lineNumber) throws InvalidFormatException Splits a lexicon line on commas, honoring MeCab-style"..."quoting with""escapes inside a quoted field. A quoted field must close on its line; MeCab reads an unclosed field silently to the line's end, but here it is rejected so a lost closing quote cannot corrupt the entry without a trace.- Parameters:
line- The line to split.file- The file the line came from, for error messages.lineNumber- The line's position in the file, for error messages.- Returns:
- The fields in order, empty fields included. Never
null. - Throws:
InvalidFormatException- Thrown if a quoted field is unterminated.
-
parseInt
Parses a decimal integer field, reporting the file and line on failure.- Parameters:
text- The field text.file- The file being read, for the error message.lineNumber- The line being read, for the error message.- Returns:
- The parsed value.
- Throws:
InvalidFormatException- Thrown if the field is not a valid integer.
-
parseCodePoint
private static int parseCodePoint(String text, Path file, int lineNumber) throws InvalidFormatException Parses a0x-prefixed hexadecimal code point fromchar.def.- Parameters:
text- The field text including the0xprefix.file- The file being read, for the error message.lineNumber- The line being read, for the error message.- Returns:
- The parsed code point, which may be in a supplementary plane.
- Throws:
InvalidFormatException- Thrown if the field does not start with the0xprefix in either case, is not a valid hexadecimal number, or names a value no Unicode code point has.
-