Class MecabDictionary

java.lang.Object
opennlp.tools.tokenize.lattice.MecabDictionary

public final class MecabDictionary extends Object
An immutable, in-memory dictionary in the MeCab directory format: lexicon entries from the *.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:
  • Field Details

  • 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

      public static MecabDictionary load(Path directory) throws IOException
      Loads a dictionary directory encoded in UTF-8.
      Parameters:
      directory - The unpacked dictionary directory. Must not be null.
      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 if directory is null.
    • load

      public static MecabDictionary load(Path directory, Charset charset) throws IOException
      Loads a dictionary directory.
      Parameters:
      directory - The unpacked dictionary directory holding the *.csv lexicon files, matrix.def, char.def, and unk.def. Must not be null.
      charset - The encoding the distribution uses, for example UTF-8 or EUC-JP. Must not be null.
      Returns:
      The loaded dictionary. Never null.
      Throws:
      InvalidFormatException - Thrown if a file is malformed or a lexicon entry's context ids are outside the matrix.def dimensions.
      IOException - Thrown if reading fails, a required file is missing, or a size limit is exceeded.
      IllegalArgumentException - Thrown if a parameter is null.
    • readLexicon

      private static void readLexicon(Path file, Charset charset, Map<String,List<MecabDictionary.WordEntry>> target, int leftSize, int rightSize, int[] entryCount) throws IOException
      Parses 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 first matrix.def dimension, which bounds right context ids.
      rightSize - The second matrix.def dimension, 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 exceeds ResourceLimits.MAX_ENTRIES.
    • readCharacterDefinition

      private static void readCharacterDefinition(Path file, Charset charset, Map<String,MecabDictionary.Category> categories, CategoryTable.Builder categoryTable) throws IOException
      Reads char.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 no DEFAULT category.
      IOException - Thrown if the file is missing or reading fails.
    • prefixMatches

      void prefixMatches(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.
      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

      MecabDictionary.Category categoryOf(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.
      Parameters:
      codePoint - The code point to classify.
      Returns:
      Its category, falling back to DEFAULT when no char.def mapping covers the code point. Never null.
    • categoriesOf

      CategoryTable.CategoryAssignment categoriesOf(int codePoint)
      Classifies a character into all categories assigned by char.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 DEFAULT when no mapping covers the code point.
    • unknownEntries

      List<MecabDictionary.WordEntry> unknownEntries(String category)
      Looks up the unknown-word templates of a category.
      Parameters:
      category - The category name.
      Returns:
      The templates, or null when the category has none.
    • isFlag

      private static boolean isFlag(String field)
      Reports whether a char.def category flag field is exactly 0 or 1.
      Parameters:
      field - The flag field text.
      Returns:
      true when the field is a recognized flag value.
    • requireFile

      private static void requireFile(Path file) throws IOException
      Checks that a required dictionary file exists.
      Parameters:
      file - The file to check.
      Throws:
      IOException - Thrown if file does not exist.
    • malformedEntry

      private static InvalidFormatException malformedEntry(Path file, int lineNumber, String detail)
      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, or null for 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

      private static int parseInt(String text, String file, int lineNumber) throws InvalidFormatException
      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 a 0x-prefixed hexadecimal code point from char.def.
      Parameters:
      text - The field text including the 0x prefix.
      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 the 0x prefix in either case, is not a valid hexadecimal number, or names a value no Unicode code point has.