Struct MorphAnalyzer

Source
pub struct MorphAnalyzer {
    pub fst: Map<Vec<u8>>,
    pub word_parses: Vec<Vec<Parse>>,
    pub tags: Vec<SmallVec<[Grammem; 8]>>,
    pub lemmas: Vec<SmallString<[u8; 16]>>,
    pub paradigms: Vec<Vanga>,
    pub lemmas_rows: Vec<Vec<u32>>,
}
Expand description

Морфологический анализатор, образованный из словаря.

Fields§

§fst: Map<Vec<u8>>§word_parses: Vec<Vec<Parse>>§tags: Vec<SmallVec<[Grammem; 8]>>§lemmas: Vec<SmallString<[u8; 16]>>§paradigms: Vec<Vanga>§lemmas_rows: Vec<Vec<u32>>

Implementations§

Source§

impl MorphAnalyzer

Source

pub fn id_forms<'a>( &'a self, word: &'a str, ids: &'a [u32], word_id: Option<u64>, grammemes: &'a Option<Vec<Grammem>>, ) -> impl Iterator<Item = (u64, &'a Parse)>

Фильтрация нужных Parse слов(а) в зависимости от запроса граммем. Возвращается итератор вместе с ParseId, индексом в fst::Map.

Source§

impl MorphAnalyzer

Source

pub fn vangovanie( &self, word: &str, ) -> Result<Option<Vec<VangovanieRes>>, ParseErr>

Предсказание слова, если оно не имеется в словаре.

Source§

impl MorphAnalyzer

Source

pub fn from_dictionary(dictionary: Dictionary, fst: PathBuf) -> MopsResult<Self>

Создание анализатора из словаря.

Source

pub fn parse_word(&self, word: &str) -> Result<ParsedWords, ParseErr>

Парсинг слова.

Source

pub fn normalized_word(&self, word: &str) -> Result<NormalizedWords, ParseErr>

Нормализация слова.

Source§

impl MorphAnalyzer

Основная функциональность связана с разбиением слова по морфемам, определением парадигм и поиском всех возможных тэгов и нормальных форм.

Source

pub fn create<P: AsRef<Path>>( dict_path: P, out_dir: P, lang: Language, ) -> MopsResult<Dictionary>

Первичное создание словаря.

dict_path - путь до словаря OpenCorpora
out_dir - место, где будет храниться fst и бинарная часть словаря для будущего открытия
language - язык, по дефолту и пока единственный, Русский.

Source

pub fn create_with_reader<P: AsRef<Path>>( dict_path: P, out_dir: P, lang: Language, ) -> MopsResult<Dictionary>

Первичное создание словаря по переданному пути с чтением из буфера.

Чтение из буфера несколько медленнее, чем из строки, но занимает сильно меньше памяти.

dict_path - путь до словаря OpenCorpora
out_dir - место, где будет храниться fst и бинарная часть словаря для будущего открытия
language - язык, по дефолту и пока единственный, Русский.

Source

pub fn init<P: AsRef<Path>>(dictionary: Dictionary, dir: P) -> MopsResult<Self>

Инициализация из словаря.

Отличается от словаря отсутствием мета-информации и тем, что поднимает в оперативную память fst-словарь.

Source

pub fn open<P: AsRef<Path>>(path: P) -> MopsResult<Self>

Открытие словаря из dict.json файла и инициализация MorphAnalyzer-а.

Source

pub fn open_from_reader<P: AsRef<Path>>(path: P) -> MopsResult<Self>

Открытие словаря из dict.json файла, используя Reader для файла, и инициализация MorphAnalyzer-а.

WARN! ОЧЕНЬ долгий процесс чтения. Рекомендуется использование только при очень ограниченной оперативной памяти.

Source

pub fn parse(&self, word: &str) -> MopsResult<ParsedWords>

Парсинг слова. Получение всех возможных результатов.

Все варианты парсинга возвращаются в отсортированном порядке, гарантируя единообразие выдачи между запусками.

Source

pub fn normalize(&self, word: &str) -> MopsResult<NormalizedWords>

Нормализация слова. Получение всех возможных результатов.

Все варианты нормализации возвращаются в отсортированном порядке, гарантируя единообразие выдачи между запусками.

Source

pub fn is_known(&self, word: &str) -> bool

Проверка слова на наличие в словаре.

Source

pub fn parse_get( &self, word: &str, index: usize, ) -> MopsResult<Option<ParsedWord>>

Парсинг слова и взятие нужного по индексу набора граммем.

Source

pub fn parse_grammemes( &self, word: &str, grammemes: Vec<Grammem>, ) -> MopsResult<Option<ParsedWord>>

Парсинг слова и взятие нужного слова в зависимости от нужного набора граммем.

Source

pub fn normalize_get( &self, word: &str, index: usize, ) -> MopsResult<Option<NormalizedWord>>

Нормализация слова и взятие по индексу формы слова с ее граммемами.

Source

pub fn normalize_grammemes( &self, word: &str, grammemes: Vec<Grammem>, ) -> MopsResult<Option<NormalizedWord>>

Нормализация слова и взятие нужного слова в зависимости от нужного набора граммем.

Source

pub fn inflect_inizio(&self, word: &str) -> MopsResult<Option<InflectWords>>

Приведение к начальной форме слова. Начальная форма может отличаться от нормализованной.

Source

pub fn inflect_forms( &self, word: &str, grammemes: Vec<Grammem>, ) -> MopsResult<Option<InflectWords>>

Приведение слова к нужной форме слова с указанными граммемами.

Source

pub fn inflect_parsed( &self, parse: ParsedWord, grammemes: Vec<Grammem>, ) -> MopsResult<Option<InflectWords>>

Приведение разобранного слова к нужной форме слова с указанными граммемами.

Source

pub fn declension(&self, word: &str) -> MopsResult<Vec<InflectWords>>

Полное склонение/спряжение слова по всем формам.

WARN: Не быстрая функция. Если есть необходимый набор слов, который нужно будет искать во всех формах в тексте, лучше сделать вызов declension() ко всем словам в начале работы приложения.

Source

pub fn declension_get( &self, word: &str, index: usize, ) -> MopsResult<Option<InflectWords>>

Полное склонение/спряжение слова и взятие нужного по индексу результата.

WARN: Не быстрая функция. Если есть необходимый набор слов, который нужно будет искать во всех формах в тексте, лучше сделать вызов declension_get() ко всем словам в начале работы приложения.

Source

pub fn declension_parsed( &self, parse: &ParsedWord, ) -> MopsResult<Option<InflectWords>>

Полное склонение/спряжение разобранного слова.

WARN: Не быстрая функция. Если есть необходимый набор слов, который нужно будет искать во всех формах в тексте, лучше сделать вызов declension_parsed() ко всем словам в начале работы приложения.

Trait Implementations§

Source§

impl Allocative for MorphAnalyzer

Source§

fn visit<'allocative_a, 'allocative_b: 'allocative_a>( &self, visitor: &'allocative_a mut Visitor<'allocative_b>, )

Source§

impl Debug for MorphAnalyzer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more