RU2753183C1 - System and method for correcting spelling errors - Google Patents

System and method for correcting spelling errors Download PDF

Info

Publication number
RU2753183C1
RU2753183C1 RU2020116676A RU2020116676A RU2753183C1 RU 2753183 C1 RU2753183 C1 RU 2753183C1 RU 2020116676 A RU2020116676 A RU 2020116676A RU 2020116676 A RU2020116676 A RU 2020116676A RU 2753183 C1 RU2753183 C1 RU 2753183C1
Authority
RU
Russia
Prior art keywords
sentence
corrections
hypotheses
correction
space
Prior art date
Application number
RU2020116676A
Other languages
Russian (ru)
Inventor
Алексей Андреевич Сорокин
Александр Сергеевич Дмитриевский
Анастасия Валентиновна Кравцова
Сергей Геннадиевич Селиверстов
Original Assignee
Федеральное государственное автономное образовательное учреждение высшего образования «Московский физико-технический институт (национальный исследовательский университет)» (МФТИ)
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Федеральное государственное автономное образовательное учреждение высшего образования «Московский физико-технический институт (национальный исследовательский университет)» (МФТИ) filed Critical Федеральное государственное автономное образовательное учреждение высшего образования «Московский физико-технический институт (национальный исследовательский университет)» (МФТИ)
Priority to RU2020116676A priority Critical patent/RU2753183C1/en
Priority to PCT/RU2020/000248 priority patent/WO2021235968A1/en
Application granted granted Critical
Publication of RU2753183C1 publication Critical patent/RU2753183C1/en

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F40/00Handling natural language data
    • G06F40/20Natural language analysis
    • G06F40/232Orthographic correction, e.g. spell checking or vowelisation
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F40/00Handling natural language data
    • G06F40/20Natural language analysis
    • G06F40/279Recognition of textual entities
    • G06F40/284Lexical analysis, e.g. tokenisation or collocates

Abstract

FIELD: text correction.
SUBSTANCE: invention relates to a system and a method for correcting spelling errors. The method includes a preparatory stage for tokenization, reducing the letter case and depunctuation, and a final stage for increasing the letter case and returning punctuation, characterized in that the tokenized sentence is read through the correction generation module and, using the language dictionary and the weighted Levenshtein metric, correction candidates are found that form a ranked space of hypotheses of words for correction, then the sentence is analyzed using the language model unit, the data of the tokenized sentence and the space of hypotheses-words is entered and a matrix of the credibility of words and corrections in the sentence is obtained, using the same unit the credibility of corrections is assessed, a space of segments-hypotheses is obtained with assessments of the credibility of segments in the context, returning to the help of the correction generation module, the gains of segments-hypotheses are assessed, a conclusion about the credibility is obtained, then, using the correction decision-making module, the space of assessed hypotheses is passed through from left to right along the sentence, and a decision is made on making edits or saving the state without editing, the corrected text is received.
EFFECT: increased efficiency of correcting spelling errors by implementing an assessment of the credibility of corrections and making decisions about correcting errors.
4 cl, 5 dwg

Description

Группа изобретений относится к области корректировки орфографических ошибок, а именно автоматической проверке правописания и исправлению опечаток в любой текстовой среде.The group of inventions relates to the field of correcting spelling errors, namely, automatic spell checking and correction of typos in any text environment.

Исправление опечаток – одна из важнейших задач компьютерной лингвистики. На ее решение направлены многочисленные технические решения, начиная с известных интегрированных программных компонентов – проверка правописания в текстовом редакторе MS Word, автоисправление в виртуальной клавиатуре портативных мобильных устройств, использующие встроенные, либо наполняемые пользовательским вводом словари – и до сложных разработок на основе машинного обучения и языковых моделей, таких как Aspell (http:// aspell.net/), Hunspell (http://hunspell.github.io/), ispell (https://www.cs.hmc. edu/~geoff/ ispell.html). Однако указанные системы не учитывают контекст корректируемого текста.Correcting typos is one of the most important tasks in computational linguistics. Numerous technical solutions are aimed at solving it, starting with well-known integrated software components - spellchecking in the MS Word text editor, auto-correction in the virtual keyboard of portable mobile devices using built-in dictionaries or dictionaries filled with user input - and to complex developments based on machine learning and language models such as Aspell (http: // aspell.net/), Hunspell (http://hunspell.github.io/), ispell (https: //www.cs.hmc.edu / ~ geoff / ispell.html ). However, these systems do not take into account the context of the corrected text.

Известна также система levenshtein_corrector_ru, разработанная в библиотеке DeepPavlov, которую использует KenLM в качестве языковой модели и LevenshteinSearcher для генерации кандидатов. Однако KenLM как языковая модель не чувствительна к перестановкам слов, что может быть критично для языков с мягким порядком слов (включая русский). Also known is the levenshtein_corrector_ru system, developed in the DeepPavlov library, which KenLM uses as a language model and LevenshteinSearcher to generate candidates. However, KenLM as a language model is not sensitive to word permutations, which can be critical for languages with a soft word order (including Russian).

Языковая модель Brill-Moore, требовательна к обучающей выборке. В связи с этим система, раскрытая в патенте US 7047493B1 (приоритет 2000-03-31, МПК G06F17/21) отличается долгим и сложным механизмом обучения при низких, по сравнению с существующими аналогами, показателях корректировки ошибок.The Brill-Moore language model is demanding on the training set. In this regard, the system disclosed in US patent 7047493B1 (priority 2000-03-31, IPC G06F17 / 21) is distinguished by a long and complex learning mechanism with low, in comparison with existing analogues, error correction rates.

Другое известное решение, Yandex.Speller (https://yandex.ru/dev/speller/), для обнаружения ошибки и подбора замены использует библиотеку машинного обучения CatBoost. Благодаря CatBoost он может расшифровывать искажённые до неузнаваемости слова («адникасниеи» → «одноклассники») и учитывать контекст при поиске опечаток («скучать музыку» → «скачать музыку»). Однако указанная система ограничена использованием в браузерах и веб-приложениях, и не определят ошибки новых слов, ещё не попавших в словари.Another well-known solution, Yandex.Speller (https://yandex.ru/dev/speller/), uses the CatBoost machine learning library to detect an error and select a replacement. Thanks to CatBoost, it can decode words distorted beyond recognition (“adnikasniei” → “classmates”) and take into account the context when searching for typos (“miss music” → “download music”). However, the specified system is limited to use in browsers and web applications, and will not detect errors in new words that have not yet been included in dictionaries.

Следующее известное решение – US 20190197099 A1 (дата публикации 27 июня 2019 г., МПК G06F17 / 27). При разработке аналога разработчики отметили, что можно создать алгоритм машинного обучения (MLA) для исправления опечатки, независимо от причины опечатки, при условии, что оно обучено на соответствующих данных обучения. И варианты осуществления указанной технологии были разработаны на основе предположения, что путем искусственного создания переформулировок слов эти перестановки могут быть использованы для обучения вышеупомянутого MLA. По меньшей мере, некоторые не ограничивающие варианты осуществления настоящей технологии направлены на создание «реалистичных опечаток» (которые пользователь с большей вероятностью сделает при вводе поискового запроса и т.п.), которые можно использовать для обучения MLA. Используя эти переформулировки, MLA обучается ранжировать и выбирать переформулированное слово, которое является правильно набранным словом. Система использует слова и символы-кандидаты и присваивает им рейтинг и оценку для определения вероятности опечатки. Недостаток указанной системы в ее нацеленности на веб-ресурсы и целевое формирование словаря замены из истории запросов пользователя.The next known solution is US 20190197099 A1 (publication date June 27, 2019, IPC G06F17 / 27). When developing an analog, the developers noted that it is possible to create a machine learning algorithm (MLA) to correct a typo, regardless of the reason for the typo, as long as it is trained on the appropriate training data. And the embodiments of this technology were developed on the assumption that by artificially creating word reformulations, these permutations can be used to train the aforementioned MLA. At least some non-limiting embodiments of the present technology are directed to creating “realistic typos” (which a user is more likely to make when entering a search query, etc.) that can be used to train MLA. Using these reformulations, MLA learns to rank and select a reformulated word that is the correctly typed word. The system uses candidate words and symbols and assigns a rating and score to them to determine the likelihood of a typo. The disadvantage of this system is in its focus on web resources and the targeted formation of a replacement dictionary from the history of user requests.

Наиболее близким аналогом является решение, описанное в US 10115055 B2 (дата публикации 30 октября 2018 г., МПК G06F17 / 27). Данное изобретение максимально подробно описывает систему и процесс обучения нейронной сети с целью глубокого изучения основанного на естественном языке, в котором: модель / машина корректирования токенизации и орфографии слова может генерировать выходные данные исправленных наборов слов; и / или модель / машина деривации семантики слова может генерировать семантически маркированные выходные данные предложений на основе соответствующих входных данных наборов слов. Указанные система и способ имеют несколько вариантов реализации в зависимости от материалов обучения - словари, пользовательский ввод, шум, базы правописания и правок, но неизменным остается результат – откорректированное предложение и процессы обучения, токенизации, семантического распознавания и маркировки лексических единиц. Достоинством аналога является широкий набор баз и методов для обучения модели, нацеленной на обработку текста из любых источников – от газет до научных текстов, а также внедрение токенизации. Однако из описания системы не ясно, каким образом принимается итоговое решение о корректировке ошибок для вывода орфографически верного решения и автоматической замены слов с опечатками. Нет проработки ошибок и их оценки, что имеет значение при машинном обучении системы.The closest analogue is the solution described in US 10115055 B2 (publication date October 30, 2018, IPC G06F17 / 27). The present invention describes in as much detail a system and process of learning a neural network for the purpose of deep learning based on natural language, in which: a model / machine for correcting tokenization and spelling of a word can generate output data of corrected sets of words; and / or the word semantics derivation model / engine may generate semantically labeled sentence output based on the corresponding input of the word sets. The specified system and method have several implementation options depending on the training materials - dictionaries, user input, noise, spelling and revision bases, but the result remains unchanged - the corrected sentence and learning processes, tokenization, semantic recognition and labeling of lexical units. The advantage of the analogue is a wide set of bases and methods for training a model aimed at processing text from any source - from newspapers to scientific texts, as well as the introduction of tokenization. However, it is not clear from the description of the system how the final decision on correcting errors is made in order to output a spelling correct solution and automatically replace words with typos. There is no elaboration of errors and their assessment, which is important in machine learning of the system.

В связи с этим актуальной является задача по созданию системы корректировки орфографии, применимой в любой текстовой среде, где на входе система получает текстовый материал с ошибками, и на выходе выдает орфографически корректный текст. Для этой цели в предложенном решении в отличие от аналогов используется существенный этап оценки правдоподобия исправлений системой и автоматическое принятие решений об исправлении по результатам предыдущих этапов.In this regard, the urgent task is to create a spelling correction system applicable in any text environment, where the system receives text material with errors at the input, and outputs a spelling correct text at the output. For this purpose, the proposed solution, in contrast to analogs, uses an essential stage of assessing the likelihood of corrections by the system and automatic decision-making on corrections based on the results of the previous stages.

Таким образом, технический результат предложенного решения заключается в повышении эффективности корректировки орфографических ошибок. Thus, the technical result of the proposed solution is to improve the efficiency of correcting spelling errors.

Предлагаемое решение заключается в том, чтобы с помощью блока языковой модели и блока модели ошибок, опираясь на ранжированные результаты обработки токенизированного текста, предоставленные языковой модели модулем генерации исправлений, система автоматически подбирала такие варианты предложений, которые бы повышали правдоподобие выходного предложения, оценивала правдоподобие предложения и отдельных слов в нем, прогнозировала модель исправления ошибок с оценкой правдоподобия исправления любой подстроки в предложении на другую подстроку и автоматически заменяла лексические единицы с ошибками на орфографически корректные.The proposed solution is that, using the language model block and the error model block, based on the ranked results of processing the tokenized text provided to the language model by the patch generation module, the system automatically selects such sentence variants that would increase the likelihood of the output sentence, evaluate the likelihood of the sentence, and individual words in it, predicted an error correction model with an assessment of the likelihood of correcting any substring in a sentence to another substring, and automatically replaced lexical units with errors with spelling correct ones.

Краткое описание чертежей.Brief description of the drawings.

Рис.1 - Представляет схему, иллюстрирующую положение и взаимосвязь блоков и модулей;Fig. 1 - Provides a diagram illustrating the position and relationship of blocks and modules;

Рис.2 – схема, иллюстрирующая порядок действий способа;Fig. 2 is a diagram illustrating the procedure for the method;

Рис.3 – иллюстрация – пример генерации гипотез исправлений сегментов предложения с оценкой штрафов за исправления;Fig. 3 is an illustration of an example of generation of hypotheses of corrections of segments of a proposal with an estimate of penalties for corrections;

Рис.4 – иллюстрация – пример построения графа гипотез-предложений;Fig. 4 is an illustration - an example of constructing a graph of hypotheses-sentences;

Рис.5 – иллюстрация – пример оценки левого и правого правдоподобий при изменении токенной длины предложения при использовании в качестве блока 4 языковой модели ELMO.Fig. 5 is an illustration - an example of evaluating the left and right likelihoods when changing the token length of a sentence when using the ELMO language model as block 4.

Далее со ссылками на представленные иллюстрирующие материалы 1-4 подробно раскрыта предложенная группа изобретений. Further, with reference to the presented illustrative materials 1-4, the proposed group of inventions is disclosed in detail.

Ссылаясь на Рис. 1, система корректировки орфографических ошибок представляет собой тесное взаимодействие заложенных в нее модулей и блоков, а именно:Referring to Fig. 1, the spelling correction system is a close interaction of the modules and blocks embedded in it, namely:

Модуль считывания и преобразования текста 1 представляет собой компонент системы на основе программного обеспечения и отвечает за подготовку текстового материала к считыванию остальными блоками и модулями системы (2-5). В указанную подготовку входит: токенизация предложений, понижение регистра букв и депунктуирование. Дополнительной функцией модуля является возвращение в первоначальный вид, но уже исправленного текста после выполнения всех процессов: повышение регистра букв и расстановка пунктуации по прежним местам. The module for reading and transforming text 1 is a software-based system component and is responsible for preparing text material for reading by the rest of the blocks and modules of the system (2-5). The specified preparation includes: tokenization of sentences, lower case letters and de-punctuation. An additional function of the module is to return to its original form, but already corrected text after performing all the processes: increasing the case of letters and placing punctuation in the same places.

Модуль генерации исправлений 2, представляющий собой компонент системы на основе программного обеспечения, осуществляет считывание токенов предложения и генерацию гипотез-сегментов. На этом этапе системное правило для каждого токена предложения генерирует кандидаты слова (и кандидаты биграммы похожие на исходный токен) близкие по взвешенному расстоянию Левенштейна. Затем проводится генерация исправлений на основе склейки слов в одно (исправление ошибочных пробелов). Для базовой гипотезы также проводится изучение «является ли токен аббревиатурой». Модуль генерации исправлений 2 принимает на вход токенизированный текст с модуля считывания и преобразования текста 1 и на выходе выдает множество гипотез токенов ранжированных по стоимости исправления. Исправления могут состоять из композиции замен, удалений, вставок, транспозиций отдельных букв слова, а также включать склейку слов в одно слово и расклейку слов в (два) слова. На этом этапе указанный модуль тесно взаимодействует с блоком модели ошибок 3. The patch generation module 2, which is a software-based system component, reads supply tokens and generates segment hypotheses. At this stage, the system rule for each token of the sentence generates word candidates (and bigram candidates similar to the original token) that are close by the weighted Levenshtein distance. Then the generation of corrections is carried out on the basis of gluing words into one (correction of erroneous spaces). For the underlying hypothesis, a study is also carried out “is the token an abbreviation”. The patch generation module 2 accepts the tokenized text from the text reading and transform module 1 as input and outputs a set of hypotheses tokens ranked by the cost of the patch. Corrections can consist of a composition of replacements, deletions, insertions, transpositions of individual letters of a word, and also include gluing words into one word and pasting words into (two) words. At this stage, the specified module closely interacts with the block of the error model 3.

Модель ошибок 3 является блоком системы на основе программного обеспечения и вместе с блоком языковой модели 4 влияют на нейросеть-составляющую системы, т.е результаты, полученные указанными блоками, являются приоритетными для системы. Блок модели ошибок 3 при взаимодействии с модулем генерации исправлений 2 по паре строк s1 и s2 дает оценку логарифмической вероятности преобразования s1 в s2: P(s1|s2) Например, вероятность P(мвма|мама) > P(мвма|гиппопотам), то есть вероятность исправления строки “мвма” на “мама” больше, чем вероятность, что автор строки “мвма” хотел написать “гиппопотам”. В предлагаемом решении используется модель ошибок, которая инкрементирует штрафы за всякое исправление. В используемом решении учитываются штрафы для специальных частотных подстрок “чо-нить” на “что-нибудь”, которые дают более низкий штраф за частотные ошибки, чем для случайных исправлений. Базовый штраф за замену буквы - 4. Однако вставка и удаление пробела, транспозиция пары смежных букв имеют более низкий штраф. Это является вышеуказанной стоимостью исправления, в соответствии со значением которой модуль генерации исправлений 2 ранжирует результаты. Дополнительно система использует оценки частотности опечаток.The error model 3 is a block of the software-based system and together with the block of the language model 4 affect the neural network-component of the system, that is, the results obtained by these blocks are priority for the system. Error model block 3, when interacting with the patch generation module 2 for a pair of lines s1 and s2, gives an estimate of the logarithmic probability of converting s1 to s2: P (s1 | s2) For example, the probability P (mvma | mom)> P (mvma | hippopotamus), then there is a greater chance of fixing the mvma line to mama than the probability that the author of the mvma line wanted to write hippo. The proposed solution uses an error model that increments the penalties for each fix. The used solution takes into account penalties for special frequency substrings “cho-thread” to “something”, which give a lower penalty for frequency errors than for random corrections. The base penalty for replacing a letter is 4. However, inserting and removing a space, the transposition of a pair of adjacent letters has a lower penalty. This is the aforementioned patch cost according to the value of which the patch generation unit 2 ranks the results. Additionally, the system uses estimates of the frequency of typos.

Блок языковой модели 4 является сердцем системы, так как выбор языковой модели напрямую влияет на финальное качество корректировки. В преимущественном варианте осуществления и для опытной практической реализации системы была использована языковая модель ELMO. Блок языковой модели представляет собой программное обеспечение и считывает результаты модуля генерации исправлений 2 и блока модели ошибок 3. На основе этих данных образуется языковая матрица, и обсчет языковой матрицы токенизированного предложения, где для каждой токен-позиции в предложении генерируется распределение вероятностей по словарю с учетом контекста остальных слов предложения. Эта матрица позволяет оценить правдоподобие замены слова в предложении на произвольное слово из словаря языковой модели. Имея гипотезы исправлений для каждого сегмента предложения, модель оценивает языковой выигрыш каждой гипотезы (languagemodeladvantage) и итоговый выигрыш (advantage). Языковой выигрыш оценивает прирост вероятности от замены исходного сегмента на гипотезу по оценке языковой модели. Итоговый выигрыш оценивается как сумма языкового выигрыша и штрафа за исправление ошибки. The language model block 4 is the heart of the system, since the choice of the language model directly affects the final quality of the correction. In an advantageous embodiment and for the experimental practical implementation of the system, the ELMO language model was used. The language model block is software and reads the results of the patch generation module 2 and the error model block 3. Based on these data, a language matrix is formed, and the language matrix of the tokenized sentence is calculated, where for each token position in the sentence, a probability distribution over the dictionary is generated, taking into account the context of the rest of the words in the sentence. This matrix allows you to assess the likelihood of replacing a word in a sentence with an arbitrary word from the dictionary of the language model. Having the hypothesis of corrections for each segment of the proposal, the model estimates the language advantage of each hypothesis (language modeladvantage) and the final benefit (advantage). The language gain estimates the increase in the probability of replacing the original segment with a hypothesis based on the assessment of the language model. The total winnings are calculated as the sum of the language winnings and the error correction penalty.

Figure 00000001
Алгоритм оценки правдоподобия слов в предложении для каждой позиции слова в конкретном предложении строит распределение вероятностей слов.
Figure 00000001
The algorithm for evaluating the likelihood of words in a sentence for each word position in a particular sentence builds a probability distribution of words.

Входное предложение: Input proposal:

Figure 00000002
Figure 00000002

Словарь языковой модели: Language Model Dictionary:

Figure 00000003
Figure 00000003

Распределение на выходе из модели это множество условных распределений – языковая матрица для предложения s): The distribution at the output of the model is a set of conditional distributions - language matrix for sentence s):

Figure 00000004
Figure 00000004

Figure 00000005
Figure 00000005

Для каждого токена wordk стоящего в токен-позиции posi в предложении s языковая модель оценивает левое и правое правдоподобия. Левое правдоподобие это оценка правдоподобия токена при условии наличия токенов слева (у которых posj: j < i). Аналогично правое правдоподобие — это правдоподобие токена при условии правого контекста (j > i).For each wordk token in token position posi in clause s, the language model evaluates the left and right likelihoods. The left-side likelihood is an estimate of the likelihood of a token given the presence of tokens on the left (with posj: j <i). Likewise, the likelihood of a token is the likelihood of a token given the right context (j> i).

Так как блок языковой модели 4 основывается на базе токенов, то орфографические ошибки, решаемые преобразованием двух или нескольких слов склеиванием нескольких токенов в один, меняют токен-индексацию в предложении - уменьшают количество токенов. Для этой ситуации применяется другая формула. При объединении двух токенов в один находящихся на позициях i и i+1 левое правдоподобие итогового токена берется из языковой матрицы на позиции i (при условии, что итоговый токен есть в словаре), а правое правдоподобие берется из колонки матрицы на позиции i + 1.Since the block of the language model 4 is based on tokens, spelling errors solved by converting two or more words by gluing several tokens into one change the token-indexing in the sentence - reduce the number of tokens. A different formula applies for this situation. When combining two tokens into one located at positions i and i + 1, the left likelihood of the final token is taken from the language matrix at position i (provided that the final token is in the dictionary), and the right likelihood is taken from the column of the matrix at position i + 1.

При увеличении количества токенов после исправления для точной оценки необходим перерасчет матрицы полученного предложения. Но с потерей точности можно оценить правдоподобие такой расклейки без переоценки языковой моделью. Для этого модель использует левое правдоподобие левого токена и правое правого токена. Левое правдоподобие правого токена и правое правдоподобие левого токена неизвестны. Модель вводит штраф за расклейку слов и считает кумулятивный выигрыш по сравнению со склеенным словом суммируя известные оценки языковой модели и штраф за расклейку (и прочие штрафы за правки, если они имеют место быть). Затем система вновь обращается к модулю генерации исправлений 2 для оценки выигрышей сегментов-гипотез.When the number of tokens is increased after the correction, for an accurate assessment, it is necessary to recalculate the matrix of the received proposal. But with a loss of accuracy, it is possible to assess the likelihood of such a sticking without re-evaluating the language model. For this, the model uses the left likelihood of the left token and the right likelihood of the right token. The left likelihood of the right token and the right likelihood of the left token are unknown. The model introduces a penalty for pasting words and calculates the cumulative gain in comparison with the glued word by summing the known estimates of the language model and the penalty for pasting (and other penalties for edits, if any). Then the system again turns to the patch generation module 2 to estimate the winnings of the hypothesis segments.

После подсчета оценок вероятности, выигрышей и правдоподобия, выполненного предыдущими модулями и блоками, все данные передаются на модуль принятия решений 5, представляющего собой системный компонент на основе алгоритма. В процессе считывания подготовленных числовых значений, алгоритм параметризуется минимальным отступом уверенности для исправления, идет последовательно по сегментам предложения и оценивает наилучшую замену по значению итогового выигрыша. Затем принимает решение об исправлении, либо сохранении написания слова и по завершении процедуры, после команды исправить/оставить, процесс переключается обратно на модуль считывания и преобразования текста 1, который возвращает текст в первоначальный вид, не затрагивая исправленные орфографические ошибки - повышает регистр букв и расставляет пунктуацию по прежним местам.After calculating the estimates of probability, winnings and likelihood performed by the previous modules and blocks, all data is transmitted to the decision-making module 5, which is a system component based on the algorithm. In the process of reading prepared numerical values, the algorithm is parameterized with the minimum confidence margin for correction, goes sequentially through the offer segments and evaluates the best replacement by the value of the final gain. Then he decides to correct or save the spelling of the word and upon completion of the procedure, after the command to correct / leave, the process switches back to the text reading and transforming module 1, which returns the text to its original form, without affecting the corrected spelling errors - increases the case of letters and places punctuation in the same places.

Система работает в режиме последовательно-параллельных задач, этапы идут друг за другом, где каждый опирается на результаты предыдущего, но разбор токенизированного предложения идет целиком, так как каждое слово-токен рассматривается в контексте других слов-токенов.The system works in the mode of sequential-parallel tasks, the stages follow one after another, where each one relies on the results of the previous one, but the parsing of the tokenized sentence goes in its entirety, since each token word is considered in the context of other token words.

Детальное описание способа корректировки орфографических ошибок по указанной системе, ссылаясь на Рис.2:A detailed description of the method for correcting spelling errors according to the specified system, referring to Fig. 2:

1. С помощью описанной системы в автоматизированном режиме посредством модуля считывания и преобразования текста 1 осуществляют препроцессинг: токенизируют предложение, понижают регистр букв и осуществляют депунктуацию.1. With the help of the described system in an automated mode, by means of the text reading and transformation module 1, preprocessing is carried out: the sentence is tokenized, the case of letters is lowered and depunctuation is carried out.

2. Через модуль генерации исправлений 2 осуществляют считывание токенизированного предложения и, используя словарь языка и взвешенную метрику Левенштейна, находят кандидаты-исправления, которые образуют ранжированное пространство гипотез слов для корректировки. 2. Through the module of generation of corrections 2, the tokenized sentence is read and, using the language dictionary and the weighted Levenshtein metric, candidates-corrections are found, which form a ranked space of hypotheses of words for correction.

3. Осуществляют анализ предложения языковой моделью. Вводят данные токенизированного предложения и пространства гипотез-слов, а блок языковой модели 4 в результате анализа выдает матрицу правдоподобий слов и исправлений в предложении в зависимости от их позиции. 3. Carry out the analysis of the sentence by the language model. The data of the tokenized sentence and the space of hypotheses-words are entered, and the block of the language model 4, as a result of the analysis, produces a matrix of likelihood of words and corrections in the sentence, depending on their position.

4. При помощи того же блока производят оценку правдоподобий исправлений, изменяющих количество токенов в предложении (исправления связанные с уменьшением количества слов и исправления связанные с увеличением числа слов в предложении). В результате этих шагов получают пространство сегментов-гипотез (включая нуль-гипотезы – сегменты без исправлений) предложения с оценками правдоподобий сегментов в контексте рассматриваемого предложения.4. Using the same block, the likelihood of corrections that change the number of tokens in a sentence is assessed (corrections associated with a decrease in the number of words and corrections associated with an increase in the number of words in a sentence). As a result of these steps, a space of segments-hypotheses (including null-hypotheses - segments without corrections) of sentences with likelihood estimates of the segments in the context of the sentence in question is obtained.

5. После этапа генерации гипотез и анализа предложения возвращаются к помощи модуля генерации исправлений 2 производят оценку выигрышей сегментов-гипотез. В простой реализации оценка представляет собой суммирование правдоподобий сегментов-гипотез и правдоподобий исправлений и вычет правдоподобия нуль-гипотезы (гипотезы без исправления), для получения выигрыша над нуль-гипотезой. Если выигрыш положительный — значит исправление правдоподобно. Если выигрыш отрицательный, то исправление неправдоподобно.5. After the stage of generating hypotheses and analyzing the proposals, they return to the help of the module for generating corrections 2 and evaluate the gains of the segments-hypotheses. In a simple implementation, the estimate is the sum of the likelihoods of the segment-hypotheses and the likelihoods of the corrections and the deduction of the likelihood of the null hypothesis (hypothesis without correction) to obtain the gain over the null hypothesis. If the gain is positive, then the correction is plausible. If the gain is negative, then the correction is implausible.

6. Далее с помощью модуля принятия решений 5 об исправлениях проходят по пространству оцененных гипотез слева-направо по предложению и принимают решение о внесении правки на одну из гипотез для данного сегмента или выборе нуль-гипотезы (оставляет сегмент предложения как в исходном предложении).6. Next, with the help of the decision-making module 5 on corrections, they pass through the space of the estimated hypotheses from left to right according to the proposal and make a decision on making an amendment to one of the hypotheses for this segment or choosing a null hypothesis (leaves the segment of the sentence as in the original sentence).

7. Финальным шагом способа является постпроцессинг посредством модуля считывания и преобразования текста 1, при котором происходит склеивание сегментов в строку-предложение и восстановление регистра слов и пунктуации в исправленном предложении.7. The final step of the method is post-processing by means of the text reading and transformation module 1, in which the segments are glued into a sentence string and the word register and punctuation in the corrected sentence are restored.

Результатом использования настоящего изобретения являются следующие преимущества:The use of the present invention results in the following advantages:

- Быстрая проверка орфографических ошибок; - Fast spell checker;

- Единовременная корректировка ошибок;- One-time error correction;

- Обучаемая гибкая система на основе нейросети и языковой модели постоянно обрабатывает данные о найденных и возможных ошибках, все время совершенствуясь и сводя орфографические ошибки на нет;- A trained flexible system based on a neural network and a language model constantly processes data about found and possible errors, constantly improving and reducing spelling errors to nothing;

- Система способна запоминать новые правила, таким образом есть возможность применения системы и в случаях с аббревиатурами и иными сложными ситуациями компьютерной лингвистики.- The system is able to memorize new rules, thus it is possible to apply the system in cases with abbreviations and other complex situations of computational linguistics.

Claims (8)

1. Система корректировки орфографических ошибок, характеризующаяся наличием модуля считывания и преобразования текста, отвечающего за токенизацию, изменение пунктуации, изменение регистра букв и блока языковой модели, производящего анализ предложений, отличающаяся тем, что содержит:1. A system for correcting spelling errors, characterized by the presence of a text reading and conversion module responsible for tokenization, changing punctuation, changing the case of letters and a block of the language model that analyzes sentences, characterized in that it contains: - модуль генерации исправлений, который на основе токенизированных предложений генерирует кандидаты слова, близкие по взвешенному расстоянию Левенштейна, и производит оценку выигрышей сегментов-гипотез,- a module for generating corrections, which, based on tokenized sentences, generates word candidates that are close by the weighted Levenshtein distance, and evaluates the winnings of hypothesis segments, - блок модели ошибок, который просчитывает вероятности исправления и инкрементирует штрафы за каждое исправление,- an error model block that calculates the probabilities of correction and increments penalties for each correction, - модуль принятия решений, который оценивает наилучшую замену по данным от других модулей и блоков и осуществляет замену при положительном результате,- a decision-making module that evaluates the best replacement based on data from other modules and blocks and carries out the replacement if the result is positive, при этом модуль генерации исправлений взаимосвязан с блоком языковой модели, который в свою очередь взаимосвязан с блоком модели ошибок.the patch generation module is interconnected with the language model block, which in turn is interconnected with the error model block. 2. Система по п. 1, отличающаяся тем, что блок языковой модели выполнен с возможностью генерации матрицы правдоподобий слов и исправлений.2. The system of claim. 1, characterized in that the language model block is configured to generate a likelihood matrix of words and corrections. 3. Система по п. 1, отличающаяся тем, что блок языковой модели выполнен на основе языковой модели ELMO.3. The system according to claim 1, characterized in that the language model block is based on the ELMO language model. 4. Способ корректировки орфографических ошибок с помощью указанной по п. 1 формулы системы, включающий подготовительный этап по токенизации, уменьшению регистра букв и депунктуации, финальный этап по увеличению регистра букв и возвращению пунктуации, отличающийся тем, что через модуль генерации исправлений осуществляют считывание токенизированного предложения и, используя словарь языка и взвешенную метрику Левенштейна, находят кандидаты-исправления, которые образуют ранжированное пространство гипотез слов для корректировки, затем осуществляют анализ предложения с помощью блока языковой модели, вводят данные токенизированного предложения и пространства гипотез-слов и получают матрицу правдоподобий слов и исправлений в предложении, при помощи того же блока производят оценку правдоподобий исправлений, получают пространство сегментов-гипотез с оценками правдоподобий сегментов в контексте, возвращаются к помощи модуля генерации исправлений и производят оценку выигрышей сегментов-гипотез, получают вывод о правдоподобности, далее с помощью модуля принятия решений об исправлениях проходят по пространству оцененных гипотез слева-направо по предложению и принимают решение о внесении правки или сохранении состояния без правки, получают откорректированный текст.4. A method for correcting spelling errors using the system specified in claim 1, including a preparatory stage for tokenization, decreasing the case of letters and depunctuation, the final stage for increasing the case of letters and returning punctuation, characterized in that the tokenized sentence is read through the correction generation module and, using the language vocabulary and the weighted Levenshtein metric, find candidate corrections that form a ranked space of word hypotheses to be corrected, then analyze the sentence using the language model block, input the data of the tokenized sentence and the word hypothesis space, and obtain a likelihood matrix of words and corrections in the proposal, using the same block, the likelihoods of the corrections are estimated, the space of the segment-hypotheses is obtained with the estimates of the likelihoods of the segments in the context, they are returned to the help of the correction generation module and the gains of the segments-hypotheses are estimated, according to they receive a conclusion about the likelihood, then, using the module for making decisions about corrections, they pass through the space of the estimated hypotheses from left to right according to the proposal and decide whether to make an amendment or save the state without editing, get the corrected text.
RU2020116676A 2020-05-21 2020-05-21 System and method for correcting spelling errors RU2753183C1 (en)

Priority Applications (2)

Application Number Priority Date Filing Date Title
RU2020116676A RU2753183C1 (en) 2020-05-21 2020-05-21 System and method for correcting spelling errors
PCT/RU2020/000248 WO2021235968A1 (en) 2020-05-21 2020-05-25 System and method for correcting orthographic errors

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2020116676A RU2753183C1 (en) 2020-05-21 2020-05-21 System and method for correcting spelling errors

Publications (1)

Publication Number Publication Date
RU2753183C1 true RU2753183C1 (en) 2021-08-12

Family

ID=77349286

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2020116676A RU2753183C1 (en) 2020-05-21 2020-05-21 System and method for correcting spelling errors

Country Status (2)

Country Link
RU (1) RU2753183C1 (en)
WO (1) WO2021235968A1 (en)

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2785207C1 (en) * 2021-12-27 2022-12-05 Общество с ограниченной ответственностью "Виртуальные Ассистенты" Method and system for automatic search and correction of errors in texts in natural language

Citations (8)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US7047493B1 (en) * 2000-03-31 2006-05-16 Brill Eric D Spell checker with arbitrary length string-to-string transformations to improve noisy channel spelling correction
WO2013191662A1 (en) * 2012-06-22 2013-12-27 National University Of Singapore Method for correcting grammatical errors of an input sentence
US9384389B1 (en) * 2012-09-12 2016-07-05 Amazon Technologies, Inc. Detecting errors in recognized text
US20170004120A1 (en) * 2015-06-30 2017-01-05 Facebook, Inc. Corrections for natural language processing
US9600469B2 (en) * 2012-08-23 2017-03-21 Sk Telecom Co., Ltd. Method for detecting grammatical errors, error detection device for same and computer-readable recording medium having method recorded thereon
US9734234B2 (en) * 2014-03-07 2017-08-15 Tata Consultancy Services Limited System and method for rectifying a typographical error in a text file
US10115055B2 (en) * 2015-05-26 2018-10-30 Booking.Com B.V. Systems methods circuits and associated computer executable code for deep learning based natural language understanding
US20190197099A1 (en) * 2017-12-27 2019-06-27 Yandex Europe Ag Method for correcting a mistyped word resulting from at least one of an inaccurate keyboard input and a wrong keyboard layout and system implementing thereof

Patent Citations (8)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US7047493B1 (en) * 2000-03-31 2006-05-16 Brill Eric D Spell checker with arbitrary length string-to-string transformations to improve noisy channel spelling correction
WO2013191662A1 (en) * 2012-06-22 2013-12-27 National University Of Singapore Method for correcting grammatical errors of an input sentence
US9600469B2 (en) * 2012-08-23 2017-03-21 Sk Telecom Co., Ltd. Method for detecting grammatical errors, error detection device for same and computer-readable recording medium having method recorded thereon
US9384389B1 (en) * 2012-09-12 2016-07-05 Amazon Technologies, Inc. Detecting errors in recognized text
US9734234B2 (en) * 2014-03-07 2017-08-15 Tata Consultancy Services Limited System and method for rectifying a typographical error in a text file
US10115055B2 (en) * 2015-05-26 2018-10-30 Booking.Com B.V. Systems methods circuits and associated computer executable code for deep learning based natural language understanding
US20170004120A1 (en) * 2015-06-30 2017-01-05 Facebook, Inc. Corrections for natural language processing
US20190197099A1 (en) * 2017-12-27 2019-06-27 Yandex Europe Ag Method for correcting a mistyped word resulting from at least one of an inaccurate keyboard input and a wrong keyboard layout and system implementing thereof

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2785207C1 (en) * 2021-12-27 2022-12-05 Общество с ограниченной ответственностью "Виртуальные Ассистенты" Method and system for automatic search and correction of errors in texts in natural language

Also Published As

Publication number Publication date
WO2021235968A1 (en) 2021-11-25

Similar Documents

Publication Publication Date Title
Nguyen et al. Survey of post-OCR processing approaches
Wang et al. A comprehensive survey of grammar error correction
Wang et al. A comprehensive survey of grammatical error correction
US11423237B2 (en) Sequence transduction neural networks
Alkanhal et al. Automatic stochastic arabic spelling correction with emphasis on space insertions and deletions
KR100911834B1 (en) Method and apparatus for correcting of translation error by using error-correction pattern in a translation system
KR20230009564A (en) Learning data correction method and apparatus thereof using ensemble score
Masmoudi et al. Transliteration of Arabizi into Arabic script for Tunisian dialect
Mondal et al. Machine translation and its evaluation: a study
Go et al. Gramatika: A grammar checker for the low-resourced Filipino language
JP2006338261A (en) Translation device, translation method and translation program
JP2010244385A (en) Machine translation device, machine translation method, and program
Kumar et al. Design and implementation of nlp-based spell checker for the tamil language
RU2753183C1 (en) System and method for correcting spelling errors
Dušek Novel methods for natural language generation in spoken dialogue systems
CN111090720B (en) Hot word adding method and device
Nabende Applying dynamic Bayesian Networks in transliteration detection and generation
Li et al. Word segmentation and morphological parsing for sanskrit
Tarnavskyi Improving sequence tagging for grammatical error correction
Li et al. Towards Robust Chinese Spelling Check Systems: Multi-round Error Correction with Ensemble Enhancement
RU2785207C1 (en) Method and system for automatic search and correction of errors in texts in natural language
Xu et al. A Multi-channel Chinese Text Correction Method Based on Grammatical Error Diagnosis
da Silva GERC: Multilingual Grammatical Error Correction for the Informal Writer
Shi Enhanced Representations and Efficient Analysis of Syntactic Dependencies Within and Beyond Tree Structures
Grella et al. Non-projective dependency parsing via latent heads representation (LHR)