""" The tokenizer that most of the models share: it is made of data, and a hook.
A language declares what it excludes, where its sentences end and how a word is replaced:
>>> class Tokenizer(RuleTokenizer):
... def replace(self, token: str) -> str:
... return token.lower()
>>> t = Tokenizer()
>>> list(t.sentence_tokenizer("Un mot. Deux mots !"))
[['un', 'mot', '.'], ['deux', 'mots', '!']]
>>> t.tokens
[(0, 'Un', 'un'), (1, 'mot', 'mot'), (2, '.', '.'), (3, 'Deux', 'deux'), (4, 'mots', 'mots'), (5, '!', '!')]
"""
import regex as re
from typing import Generator, List, Tuple
from .memorizing import MemorizingTokenizer
from .utils import chars, regexps
from .utils.excluder import CharRegistry, ExcluderPrototype
[docs]
class RuleTokenizer(MemorizingTokenizer):
""" Cuts a text in sentences, then in words, keeps in memory what it replaced
What a language gives:
- `excluders(registry)`: the tokens that are put aside, and given back after the tagging (references, abbreviations...)
- `replace(token)`: what the tagger sees of a token that no excluder took (`treated` in the output). By default,
the token itself
- `re_sentence_boundaries`, `re_add_space_around_punct`: where the sentences end, and the punctuation to put apart
- `char_registry()`: the registry of the characters that the excluders write in the text while they work
`replacer` is the whole decision (excluders first, then `replace`): a language can still take it over.
"""
re_add_space_around_punct = re.compile(regexps.NON_WORD_NON_SPACE)
re_sentence_boundaries = re.compile(r"([" + chars.DOTS_EXCEPT_APOSTROPHES + r"]+\s*)+")
# `lower` is a boolean that is true only if it is `True` for some languages (a legacy of their code)
strict_lower = False
def __init__(self):
super(RuleTokenizer, self).__init__()
self.tokens = []
self.char_registry: CharRegistry = self.new_char_registry()
self.normalizers: Tuple[ExcluderPrototype, ...] = tuple(self.excluders(self.char_registry))
[docs]
def new_char_registry(self) -> CharRegistry:
return CharRegistry()
[docs]
def excluders(self, registry: CharRegistry) -> Tuple[ExcluderPrototype, ...]:
return ()
[docs]
def replace(self, token: str) -> str:
return token
@staticmethod
def _sentence_tokenizer_merge_matches(match):
""" Best way we found to deal with repeating groups"""
start, end = match.span()
return match.string[start:end] + "<SPLIT>"
def _real_sentence_tokenizer(self, string: str) -> List[str]:
string = self.re_sentence_boundaries.sub(self._sentence_tokenizer_merge_matches, string)
for excluder in self.normalizers:
string = excluder.after_sentence_tokenizer(string)
return string.split("<SPLIT>")
def _real_word_tokenizer(self, text: str, lower: bool = False) -> List[str]:
if (lower is True) if self.strict_lower else lower:
text = text.lower()
return text.split()
[docs]
def sentence_tokenizer(self, text: str, lower: bool = False) -> Generator[List[str], None, None]:
sentences = list()
data = self.normalizer(text)
for sent in self._real_sentence_tokenizer(data):
sent = sent.strip()
if sent:
sentences.append(self.word_tokenizer(sent))
yield from sentences
[docs]
def normalizer(self, data: str) -> str:
for excluder in self.normalizers:
data = excluder.before_sentence_tokenizer(data)
return self.re_add_space_around_punct.sub(r" \g<2> ", data)
[docs]
def exclude_patterns(self) -> list:
""" What the data iterator must not give to the tagger: the tokens that an excluder puts aside """
return [excluder.exclude_regexp for excluder in self.normalizers if excluder.exclude_regexp]
[docs]
def excluded(self, token: str) -> bool:
""" Is the token one that an excluder keeps as it is? """
return any(not excluder.can_be_replaced and excluder.exclude_regexp.match(token) for excluder in self.normalizers)
[docs]
def replacer(self, token: str) -> str:
if self.excluded(token):
return token
return self.replace(token)