Extract character n-grams with boundary markers

Why it matters Character n-gram features still power fast language ID and spam filters.

Subword models like fastText represent a word by its character n-grams, with markers at the ends.

Write char_ngrams(word, nmin, nmax). Wrap the word as "<" + word + ">", then return every substring of length nmin to nmax, ordered by n then by start position.

Signaturedef char_ngrams(word, nmin, nmax)

Example

char_ngrams("ab", 2, 3) is ["<a", "ab", "b>", "<ab", "ab>"].

Understand the idea

fastText style models represent a word as a bag of its character n-grams, so related or rare words such as 'running' and 'runner' share pieces. Markers '<' and '>' are added at the word ends so a prefix like '<ru' is different from 'ru' in the middle of a word. Worked example: char_ngrams('cat', 3, 4). The wrapped word is '<cat>', 5 characters. Length 3 n-grams starting at positions 0, 1, 2: '<ca', 'cat', 'at>'. Length 4 n-grams starting at 0 and 1: '<cat', 'cat>'. Result: ['<ca', 'cat', 'at>', '<cat', 'cat>']. Rule: w = '<' + word + '>'; for n from nmin to nmax, for start from 0 to len(w) - n inclusive, append w[start : start + n]. Order is by n first, then by start position. The last valid start is len(w) - n, so a loop that stops one early loses the final n-gram such as 'at>'. Used in: fastText embeddings for out-of-vocabulary words, language identification and spelling-robust text features.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplechar_ngrams('ab', 2, 3)
  • Sample 2: trigramschar_ngrams('where', 3, 3)
  • Test 3: too shortchar_ngrams('a', 4, 5)