Text Processing Pipeline

A tokenizer can change the text before it tokenizes it, and the tokens after: character filters run on the text, and token filters on the tokens. In the C API a filter is appended to a LinderaTokenizerBuilder, and the filters run in the order they were appended.

Input Text
  --> Character Filters (preprocessing)
  --> Tokenization
  --> Token Filters (postprocessing)
  --> Output Tokens

[!NOTE] This page shows a few commonly used filters as examples -- it is not the complete list. See Filters for the full, authoritative catalogue of every character and token filter that lindera-analysis ships, including parameters and examples.

Appending a filter

LinderaStatus lindera_tokenizer_builder_append_character_filter(LinderaTokenizerBuilder *builder,
                                                                const uint8_t *kind, size_t kind_len,
                                                                const uint8_t *args_json,
                                                                size_t args_json_len,
                                                                LinderaError **error);
LinderaStatus lindera_tokenizer_builder_append_token_filter(LinderaTokenizerBuilder *builder,
                                                            const uint8_t *kind, size_t kind_len,
                                                            const uint8_t *args_json,
                                                            size_t args_json_len,
                                                            LinderaError **error);

kind is the name of the filter, and args_json its arguments as the text of a JSON object. The empty text (NULL, 0) is no arguments. Text is a pointer and a length, as everywhere in the API (see Lindera C).

const char *kind = "unicode_normalize";
const char *args = "{\"kind\":\"nfkc\"}";

lindera_tokenizer_builder_append_character_filter(builder, (const uint8_t *)kind, strlen(kind),
                                                  (const uint8_t *)args, strlen(args), &error);
lindera_tokenizer_builder_append_token_filter(builder, (const uint8_t *)"lowercase", 9, NULL, 0,
                                              &error);

Arguments that are no JSON object fail at once, with LINDERA_STATUS_INVALID_ARGUMENT. A name that is no filter, and arguments a filter does not take, fail when lindera_tokenizer_builder_build builds the tokenizer.

A tokenizer made with lindera_tokenizer_new has no filters; a builder makes one with filters.

Character Filters

Character filters transform the input text before tokenization. The last column is what the filter does to a text, with IPADIC.

FilterArgumentsWhat it doesExample
unicode_normalize{"kind":"nfkc"}Applies a Unicode normalization form: nfc, nfkc, nfd or nfkdLindera becomes Lindera
mapping{"mapping":{"リンデラ":"Lindera"}}Replaces the strings that are the keys of a table with their valuesリンデラは becomes Lindera / は
japanese_iteration_mark{"normalize_kanji":true,"normalize_kana":true}Replaces the Japanese iteration marks (odoriji) with the characters they repeat時々 becomes 時時

Token Filters

Token filters transform or remove tokens after tokenization. The last column is what the filter does to the tokens of a text, with IPADIC.

FilterArgumentsWhat it doesExample
lowercasenoneConverts the surfaces of the tokens to lower caseLindera becomes lindera
japanese_base_formnoneReplaces an inflected form with its base (dictionary) form, from the details of the dictionary食べ / た becomes 食べる / た
japanese_stop_tags{"tags":["助詞,格助詞,一般","助詞,係助詞","助詞,連体化","助動詞"]}Removes the tokens whose part of speech is one of the tags東京 / は / 晴れ / です becomes 東京 / 晴れ
japanese_keep_tags{"tags":["名詞,一般"]}Keeps only the tokens whose part of speech is one of the tags形態素 / 解析 / を / 行う becomes 形態素
japanese_katakana_stem{"min":3}Removes a trailing prolonged sound mark from the katakana tokens longer than min charactersライブラリー becomes ライブラリ

[!NOTE] Tags are normalized to exactly four comma-separated levels (missing levels are padded with *) and compared for exact equality against the four part-of-speech details of each token, starting at the field named part_of_speech in the dictionary schema (or at the first detail when the schema has no such field). A bare 助詞 therefore never matches IPADIC particle tokens — they always carry a subcategory such as 助詞,係助詞 — while a bare 助動詞 does match, because auxiliary verbs have no subcategory (助動詞,*,*,*).

Complete Pipeline Example

The program below is lindera-c/examples/pipeline.c. It combines two character filters and three token filters into a single pipeline:

/* Tokenizes a text through a pipeline: character filters change the text,
 * the tokenizer splits it, and token filters change or remove the tokens.
 *
 *     pipeline [<dictionary> [<text>]]
 *
 * <dictionary> is the path of a directory that holds a built dictionary, or
 * `embedded://<name>` for a dictionary the library was built with. The
 * default is `embedded://ipadic`. <text> is UTF-8. The filters are for a
 * dictionary with the parts of speech of IPADIC.
 */

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

#include "lindera.h"

/* A filter of the pipeline: its name, and its arguments as a JSON object,
 * or NULL when it takes none. */
typedef struct Filter {
    const char *kind;
    const char *args;
} Filter;

/* The character filters run on the text, in this order. */
static const Filter CHARACTER_FILTERS[] = {
    /* Full-width letters become half-width (NFKC). */
    {"unicode_normalize", "{\"kind\":\"nfkc\"}"},
    /* Iteration marks become the characters they repeat. */
    {"japanese_iteration_mark", "{\"normalize_kanji\":true,\"normalize_kana\":true}"},
};

/* The token filters run on the tokens, in this order. */
static const Filter TOKEN_FILTERS[] = {
    /* An inflected word becomes its base form. */
    {"japanese_base_form", NULL},
    /* Particles, auxiliary verbs and punctuation are removed. */
    {"japanese_stop_tags",
     "{\"tags\":[\"助詞,格助詞,一般\",\"助詞,係助詞\",\"助詞,連体化\",\"助動詞\",\"記号,句点\",\"記号,読点\"]}"},
    /* Letters become lower case. */
    {"lowercase", NULL},
};

/* Prints what failed with the message of the error, frees the error, and
 * returns the exit code of a failure. */
static int fail(const char *what, LinderaStatus status, LinderaError *error) {
    LinderaStr message = lindera_error_message(error);

    fprintf(stderr, "%s: %s: %.*s\n", what, lindera_status_name(status), (int)message.len,
            (const char *)message.ptr);
    lindera_error_free(error);
    return 1;
}

int main(int argc, char **argv) {
    const char *dictionary = argc > 1 ? argv[1] : "embedded://ipadic";
    const char *text = argc > 2 ? argv[2] : "Linderaは形態素解析を行うライブラリです。";
    LinderaTokenizerBuilder *builder = NULL;
    LinderaTokenizer *tokenizer = NULL;
    LinderaResult *result = NULL;
    LinderaTokens tokens;
    LinderaError *error = NULL;
    LinderaStatus status;
    size_t i;
    size_t j;

    status = lindera_tokenizer_builder_new(&builder, &error);
    if (status != LINDERA_STATUS_OK) {
        return fail("lindera_tokenizer_builder_new", status, error);
    }
    status = lindera_tokenizer_builder_set_dictionary(builder, (const uint8_t *)dictionary,
                                                      strlen(dictionary), &error);

    /* A filter is appended by its name, with its arguments as the text of a
     * JSON object. The empty text (NULL, 0) is no arguments. */
    for (i = 0; status == LINDERA_STATUS_OK && i < sizeof(CHARACTER_FILTERS) / sizeof(CHARACTER_FILTERS[0]); i++) {
        const Filter *filter = &CHARACTER_FILTERS[i];

        status = lindera_tokenizer_builder_append_character_filter(
            builder, (const uint8_t *)filter->kind, strlen(filter->kind), (const uint8_t *)filter->args,
            filter->args != NULL ? strlen(filter->args) : 0, &error);
    }
    for (i = 0; status == LINDERA_STATUS_OK && i < sizeof(TOKEN_FILTERS) / sizeof(TOKEN_FILTERS[0]); i++) {
        const Filter *filter = &TOKEN_FILTERS[i];

        status = lindera_tokenizer_builder_append_token_filter(
            builder, (const uint8_t *)filter->kind, strlen(filter->kind), (const uint8_t *)filter->args,
            filter->args != NULL ? strlen(filter->args) : 0, &error);
    }
    /* A name that is no filter, or arguments a filter does not take, fail
     * here, when the tokenizer is built. */
    if (status == LINDERA_STATUS_OK) {
        status = lindera_tokenizer_builder_build(builder, &tokenizer, &error);
    }
    lindera_tokenizer_builder_free(builder);
    if (status != LINDERA_STATUS_OK) {
        return fail("building the tokenizer", status, error);
    }

    status = lindera_tokenizer_tokenize(tokenizer, (const uint8_t *)text, strlen(text), &result,
                                        &tokens, &error);
    if (status != LINDERA_STATUS_OK) {
        lindera_tokenizer_free(tokenizer);
        return fail("lindera_tokenizer_tokenize", status, error);
    }
    for (i = 0; i < tokens.len; i++) {
        const LinderaToken *token = &tokens.tokens[i];

        printf("%.*s\t", (int)token->surface.len, (const char *)token->surface.ptr);
        for (j = 0; j < token->details_len; j++) {
            printf("%s%.*s", j == 0 ? "" : ",", (int)token->details[j].len,
                   (const char *)token->details[j].ptr);
        }
        printf("\n");
    }
    printf("EOS\n");

    lindera_result_free(result);
    lindera_tokenizer_free(tokenizer);
    return 0;
}

Compile it against an installed library (see Installation) and run it with the path of a dictionary:

export PKG_CONFIG_PATH="$PWD/dist/lib/pkgconfig"
cc -o pipeline lindera-c/examples/pipeline.c $(pkg-config --cflags --libs lindera)
LD_LIBRARY_PATH="$PWD/dist/lib" ./pipeline /path/to/lindera-ipadic

Expected output:

lindera    名詞,固有名詞,組織,*,*,*,*,*,*
形態素    名詞,一般,*,*,*,*,形態素,ケイタイソ,ケイタイソ
解析    名詞,サ変接続,*,*,*,*,解析,カイセキ,カイセキ
行う    動詞,自立,*,*,五段・ワ行促音便,基本形,行う,オコナウ,オコナウ
ライブラリ    名詞,一般,*,*,*,*,ライブラリ,ライブラリ,ライブラリ
EOS

In this pipeline:

  1. unicode_normalize converts full-width characters to half-width (NFKC normalization)
  2. japanese_iteration_mark resolves iteration marks
  3. japanese_base_form converts inflected tokens to base form
  4. japanese_stop_tags removes particles, auxiliary verbs, and punctuation
  5. lowercase normalizes alphabetic characters to lowercase