Source code for janome.charfilter

# -*- coding: utf-8 -*-

# Copyright 2015 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import unicodedata

[docs]class CharFilter(object): u""" Base CharFilter class. A CharFilter modifies or transforms the input text according to the rule described in apply() method. Subclasses must implement apply() method. Added in *version 0.3.4* """
[docs] def filter(self, text): return self.apply(text)
[docs] def apply(self, text): raise NotImplementedError
[docs]class RegexReplaceCharFilter(CharFilter): u""" RegexReplaceCharFilter replaces string matched with a regular expression pattern to replacement string. Added in *version 0.3.4* """
[docs] def __init__(self, pat, repl): """ Initialize RegexReplaceCharFilter with a regular expression pattern string and replacement. :param pattern: regular expression string. :param repl: replacement string. """ self.pattern = re.compile(pat) self.replacement = repl
[docs] def apply(self, text): return re.sub(self.pattern, self.replacement, text)
[docs]class UnicodeNormalizeCharFilter(CharFilter): u""" UnicodeNormalizeCharFilter normalizes Unicode string. Added in *version 0.3.4* """
[docs] def __init__(self, form='NFKC'): """ Initialize UnicodeNormalizeCharFilter with normalization form. See also `unicodedata.normalize <https://docs.python.org/3.6/library/unicodedata.html#unicodedata.normalize>`_ for details. :param form: (Optional) normalization form. valid values for *form* are 'NFC', 'NFKC', 'NFD', and 'NFKD'. default is 'NFKC' """ self.form = form
[docs] def apply(self, text): return unicodedata.normalize(self.form, text)