Files
post-moderation/ai-moderation/app/moderation/profanity/lemmatizer.py
2026-10-20 00:37:43 +03:00

28 lines
826 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from functools import lru_cache
import pymorphy3
class Lemmatizer:
def __init__(self):
self.morph = pymorphy3.MorphAnalyzer()
# Разбор pymorphy — самое дорогое в детекторе, а слова повторяются
self._normalize_cached = lru_cache(maxsize=50_000)(self._normalize)
self._is_known_cached = lru_cache(maxsize=50_000)(self.morph.word_is_known)
def is_known(self, word: str) -> bool:
"""Есть ли слово в словаре pymorphy (обычное слово, а не сленг/опечатка)."""
return self._is_known_cached(word)
def _normalize(self, word: str) -> str:
result = self.morph.parse(word)
return result[0].normal_form
def normalize(
self,
word: str
) -> str:
return self._normalize_cached(word)