Меню

Исправление грамматических ошибок python

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

Первая программа, реализующая проверку орфографии, была написана в 1971 году для DEC PDP-10. Названный SPELL, он был способен выполнять только простые сравнения слов и обнаруживать различия в одной или двух буквах. По мере развития аппаратного и программного обеспечения появляются и средства проверки орфографии. Современные средства проверки правописания способны обрабатывать морфологию и использовать статистику для улучшения предложений.

Python предлагает множество модулей для этих целей, что делает написание простой проверки орфографии легким 20-минутным испытанием.

Одной из этих библиотек является TextBlob, которая используется для обработки естественного языка и предоставляет интуитивно понятный API для работы.

В этой статье мы рассмотрим, как реализовать исправление орфографии в Python с помощью TextBlob.

Установка

Во-первых, нам нужно установить TextBlob, поскольку он не предустановлен. Откройте консоль и установите его с помощью pip:

Это должно установить все, что нам нужно для этого проекта. По окончании установки вывод консоли должен включать что-то вроде:

Successfully installed click-7.1.2 joblib-0.17.0 nltk-3.5 regex-2020.11.13 textblob-0.15.3

TextBlob построен на основе NLTK, поэтому он также поставляется с установкой.

Функция correct()

Самый простой способ исправить вводимый текст — использовать метод correct(). В качестве примера мы будем использовать абзац из книги Чарльза Дарвина «О происхождении видов», которая является частью общественного достояния и упакована в файл с именем text.txt.

Кроме того, мы добавим несколько умышленных орфографических ошибок:

As far as I am abl to judg, after long attnding to the sbject, the condiions of lfe apear to act in two ways—directly on the whle organsaton or on certin parts alne and indirectly by afcting the reproducte sstem. Wit respct to te dirct action, we mst bea in mid tht in every cse, as Profesor Weismann hs latly insistd, and as I have inidently shwn in my wrk on "Variatin undr Domesticcation," thcere arae two factrs: namly, the natre of the orgnism and the natture of the condiions. The frmer sems to be much th mre importannt; foor nealy siimilar variations sometimes aris under, as far as we cn juddge, disimilar conditios; annd, on te oter hannd, disssimilar variatioons arise undder conditions which aappear to be nnearly uniiform. The efffects on tthe offspring arre ieither definnite or in definite. They maay be considdered as definnite whhen allc or neearly all thhe ofefspring off inadividuals exnposed tco ceertain conditionas duriing seveal ggenerations aree moodified in te saame maner.

Это полный орфографических ошибок текст, почти в каждом слове. Давайте напишем простой скрипт, используя TextBlob, чтобы исправить эти ошибки и распечатать их обратно в консоль:

from textblob import TextBlob

with open("text.txt", "r") as f:        # Opening the test file with the intention to read
    text = f.read()                     # Reading the file
    textBlb = TextBlob(text)            # Making our first textblob
    textCorrected = textBlb.correct()   # Correcting the text
    print(textCorrected)

Если вы раньше работали с TextBlob, этот алгоритм будет вам знаком. Мы прочитали файл и его содержимое и создали экземпляр TextBlob, передав содержимое конструктору.

Затем мы запускаем функцию correct() в этом экземпляре для исправления орфографии.

После запуска приведенного выше сценария вы должны получить примерно такой результат:

Is far as I am all to judge, after long attending to the subject, the conditions of life appear to act in two ways—directly on the while organisation or on certain parts alone and indirectly by acting the reproduce system. It respect to te direct action, we must be in mid the in every case, as Professor Weismann he lately insisted, and as I have evidently shown in my work on "Variation under Domesticcation," there are two facts: namely, the nature of the organism and the nature of the conditions. The former seems to be much th are important; for nearly similar variations sometimes arms under, as far as we in judge, similar condition; and, on te other hand, disssimilar variations arise under conditions which appear to be nearly uniform. The effects on the offspring are either definite or in definite. They may be considered as definite when all or nearly all the offspring off individuals exposed to certain conditions during several generations are modified in te same manner.

Насколько верна коррекция орфографии TextBlob?

Как видим, в тексте все еще есть орфографические ошибки. Слова вроде "abl" должны были быть "able", а не "all". Хотя даже с ними все равно лучше оригинала.

Теперь возникает вопрос, насколько это лучше?

Следующий фрагмент кода представляет собой простой сценарий, который проверяет, насколько хорошо TextBlob исправляет ошибки, на основе этого примера:

from textblob import TextBlob

# A function that compares two texts and returns 
# the number of matches and differences
def compare(text1, text2):  
    l1 = text1.split()
    l2 = text2.split()
    good = 0
    bad = 0
    for i in range(0, len(l1)):
        if l1[i] != l2[i]:
            bad += 1
        else:
            good += 1
    return (good, bad)

# Helper function to calculate the percentage of misspelled words
def percentageOfBad(x):
    return (x[1] / (x[0] + x[1])) * 100

Теперь, используя эти две функции, давайте проведем быстрый анализ:

with open("test.txt", "r") as f1: # test.txt contains the same typo-filled text from the last example 
    t1 = f1.read()

with open("original.txt", "r") as f2: # original.txt contains the text from the actual book 
    t2 = f2.read()

t3 = TextBlob(t1).correct()

mistakesCompOriginal = compare(t1, t2)
originalCompCorrected = compare(t2, t3)
mistakesCompCorrected = compare(t1, t3)

print("Mistakes compared to original ", mistakesCompOriginal)
print("Original compared to corrected ", originalCompCorrected)
print("Mistakes compared to corrected ", mistakesCompCorrected, "n")

print("Percentage of mistakes in the test: ", percentageOfBad(mistakesCompOriginal), "%")
print("Percentage of mistakes in the corrected: ", percentageOfBad(originalCompCorrected), "%")
print("Percentage of fixed mistakes: ", percentageOfBad(mistakesCompCorrected), "%", "n")

Запустив его, вы распечатаете:

Mistakes compared to original  (126, 194)
Original compared to corrected  (269, 51)
Mistakes compared to corrected  (145, 175) 

Percentage of mistakes in the test:  60.62499999999999 %
Percentage of mistakes in the corrected:  15.937499999999998 %
Percentage of fixed mistakes:  54.6875 % 

Как мы видим, методу correct удалось уменьшить процент орфографических ошибок с 60,6% до 15,9%, что довольно неплохо, однако есть небольшая загвоздка. Он исправил 54,7% слов, так почему все еще остается 15,9% ошибок?

Ответ — чрезмерное исправление. Иногда он может изменить слово, которое написано правильно, например, первое слово в нашем примере текста, где "As" было исправлено "Is". В других случаях ему просто не хватает информации о слове и контексте, чтобы сказать, какое слово пользователь намеревался ввести, поэтому он догадывается, что его следует заменить "whl" на "while" вместо "whole".

Не существует идеального корректора орфографии, потому что большая часть разговорной речи зависит от контекста, так что имейте это в виду. В большинстве случаев ошибок гораздо меньше, чем в нашем примере, поэтому TextBlob должен работать достаточно хорошо для обычного пользователя.

Обучающий TextBlob с настраиваемыми наборами данных

Что, если вы хотите проверить орфографию на другом языке, который не поддерживается TextBlob из коробки? Или, может быть, вы хотите быть немного точнее? Что ж, может быть способ добиться этого. Все сводится к тому, как работает проверка орфографии в TextBlob.

TextBlob использует статистику использования слов на английском языке, чтобы делать разумные предложения по поводу того, какие слова следует исправить. Он хранит эту статистику в файле с именем en-spelling.txt, но также позволяет вам создать свой собственный файл статистики использования слов.

Попробуем сделать такой для нашего примера Дарвина. Мы будем использовать все слова из «Происхождения видов» для обучения. Вы можете использовать любой текст, просто убедитесь, что в нем достаточно слов, имеющих отношение к тексту, который вы хотите исправить.

В нашем случае остальная часть книги предоставит отличный контекст и дополнительную информацию, которая потребуется TextBlob для более точного исправления.

Перепишем скрипт:

from textblob.en import Spelling        
import re

textToLower = ""

with open("originOfSpecies.txt","r") as f1:           # Open our source file
	text = f1.read()                                  # Read the file                 
	textToLower = text.lower()                        # Lower all the capital letters

words = re.findall("[a-z]+", textToLower)             # Find all the words and place them into a list    
oneString = " ".join(words)                           # Join them into one string

pathToFile = "train.txt"                              # The path we want to store our stats file at
spelling = Spelling(path = pathToFile)                # Connect the path to the Spelling object
spelling.train(oneString, pathToFile)                 # Train

Если мы заглянем в файл train.txt, то увидим:

a 3389
abdomen 3
aberrant 9
aberration 5
abhorrent 1
abilities 1
ability 4
abjectly 1
able 54
ably 5
abnormal 17
abnormally 2
abodes 2
...

Это означает, что слово "a" отображается как слово 3389 раз, а "ably"только 5 раз. Чтобы проверить эту обученную модель, мы будем использовать suggest(text) вместо correct(text), который представляет собой список кортежей доверия слов. Первым элементом в списке будет слово, в котором он уверен, поэтому мы можем получить к нему доступ через suggest(text)[0][0].

Обратите внимание, что это может быть медленнее, поэтому проверяйте орфографию слово за словом, так как сброс огромных объемов данных может привести к сбою:

from textblob.en import Spelling        
from textblob import TextBlob

pathToFile = "train.txt" 
spelling = Spelling(path = pathToFile)
text = " "

with open("test.txt", "r") as f: 
	text = f.read()

words = text.split()
corrected = " "
for i in words :
    corrected = corrected +" "+ spelling.suggest(i)[0][0] # Spell checking word by word

print(corrected)

И теперь это приведет к:

As far as I am all to judge after long attending to the subject the conditions of life appear to act in two ways—directly on the whole organisation or on certain parts alone and indirectly by acting the reproduce system It respect to the direct action we most be in mid the in every case as Professor Weismann as lately insisted and as I have incidently shown in my work on "Variatin under Domesticcation," there are two facts namely the nature of the organism and the nature of the conditions The former seems to be much th are important for nearly similar variations sometimes arise under as far as we in judge dissimilar conditions and on the other hand dissimilar variations arise under conditions which appear to be nearly uniform The effects on the offspring are either definite or in definite They may be considered as definite when all or nearly all the offspring off individuals exposed to certain conditions during several generations are modified in the same manner.

Это исправляет примерно 2 из 3 слов с ошибками, что довольно хорошо, учитывая запуск без особого контекста.

Autocorrect

build
Downloads
Average time to resolve an issue
Code style: black

Spelling corrector in python. Currently supports English, Polish, Turkish, Russian, Ukrainian, Czech, Portuguese, Greek, Italian, Vietnamese, French and Spanish, but you can easily add new languages.

Based on: https://github.com/phatpiglet/autocorrect and Peter Norvig’s spelling corrector.

Installation

Examples

>>> from autocorrect import Speller
>>> spell = Speller()
>>> spell("I'm not sleapy and tehre is no place I'm giong to.")
"I'm not sleepy and there is no place I'm going to."

>>> spell = Speller('pl')
>>> spell('ptaaki latatją kluczmm')
'ptaki latają kluczem'

Speed

%timeit spell("I'm not sleapy and tehre is no place I'm giong to.")
373 µs ± 2.09 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit spell("There is no comin to consiousnes without pain.")
150 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As you see, for some words correction can take ~200ms. If speed is important for your use case (e.g. chatbot) you may want to use option ‘fast’:

spell = Speller(fast=True)
%timeit spell("There is no comin to consiousnes without pain.")
344 µs ± 2.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Now, the correction should always work in microseconds, but words with double typos (like ‘consiousnes’) won’t be corrected.

OCR

When cleaning up OCR, replacements are the large majority of errors. If this is the case, you may want to use the option ‘only_replacements’:

spell = Speller(only_replacements=True)

Custom word sets

If you wish to use your own set of words for autocorrection, you can pass an nlp_data argument:

spell = Speller(nlp_data=your_word_frequency_dict)

Where your_word_frequency_dict is a dictionary which maps words to their average frequencies in your text. If you want to change the default word set only a bit, you can just edit spell.nlp_data parameter, after spell was initialized.

Adding new languages

First, define special letters, by adding entries in word_regexes and alphabets dicts in autocorrect/constants.py.

Now, you need a bunch of text. Easiest way is to download wikipedia.
For example for Russian you would go to:
https://dumps.wikimedia.org/ruwiki/latest/
and download ruwiki-latest-pages-articles.xml.bz2

bzip2 -d ruiwiki-latest-pages-articles.xml.bz2

After that:

First, edit the autocorrect.constants dictionaries in order to accommodate regexes and dictionaries for your language.

Then:

>>> from autocorrect.word_count import count_words
>>> count_words('ruwiki-latest-pages-articles.xml', 'ru')
tar -zcvf autocorrect/data/ru.tar.gz word_count.json

For the correction to work well, you need to cut out rarely used words. First, in test_all.py, write test words for your language, and add them to optional_language_tests the same way as it’s done for other languages. It’s good to have at least 30 words. Now run:

python test_all.py find_threshold ru

and see which threshold value has the least badly corrected words. After that, manually delete all the words with less occurences than the threshold value you found, from the file in hi.tar.gz (it’s already sorted so it should be easy).

To distribute this language support to others, you will need to upload your tar.gz file to IPFS (for example with Pinata, which will pin this file so it doesn’t disappear), and then add it’s path to ipfs_paths in constants.py. (tip: first put this file inside the folder, and upload the folder to IPFS, for the downloaded file to have the correct filename)

Good luck!

Зачем это нужно

При переводах текстов удобно иметь программу, которая не только находит грамматические ошибки, но и предлагает варианты замены неправильно написанного слова. В отличии от известных текстовых процессоров такая программа должна иметь простую и быструю смену языков проверки при их достаточном количестве. Нужно также предусмотреть фильтр для исключения непереводимых обозначений. Всё перечисленное можно реализовать на Python, Для этого нужно скачать библиотеку PyEnchant, например здесь[1]. Настроить эту библиотеку и добавить словари для русского языка.

Код программы

Модули библиотеки и пустой словарь для названия языка.

# -*- coding: utf-8 -*-
import enchant
from enchant.checker import SpellChecker
from enchant.tokenize import EmailFilter, URLFilter

Передача данных при выборе языка в программу.

def get(event):
        t=str(l.get(event.widget.curselection()))
        w['key']=0
        w['key']=t
        lab = tk.Label(root, text="", font="Arial 12")
        lab.grid_remove()
        lab = tk.Label(root, text= "Выбран язык -%s--Ввод: поля 1-текст, 2-слово. Вывод поле 3-результат"%t, font="Arial 12")
        lab.grid(row=0, column=0)

Проверка правописания одного слова.

def pravopus():
        t=w['key']
        d = enchant.Dict(t)   
        tex=txt_0.get(1.0, END).strip()
        if len(tex)!=0:
                m=d.check(tex)
                if m:
                        txt.insert(END, "Слово-%s-написано правильноn"%tex)
                else:
                        txt.insert(END, "Слово--%s- написано не правильно, нужно так-%s- n"%(tex,str(d.suggest(tex))))
        elif len(tex)==0:
                txt.insert(END, "Введите слово!!!n")

Проверка правописания фрагмента текста с исключением Email и URL.

def tokenise():
        try:
                t=w['key']
                txt.delete(1.0, END)
                p= enchant.Dict(t)
                d=  SpellChecker(t,filters=[EmailFilter,URLFilter])
                tex=txt_1.get(1.0, END).strip()
                d.set_text(tex)
                k=0
                for err in d:
                        k=k+1
                        txt.insert(END, "ERROR:",err.word, p.suggest(err.word))
                        txt.insert(END, "n")
                if k==0:
                        txt.insert(END, 'Предложение написано правильноn')
        except:
                txt.insert(END, "Ошибка ввода!!!n")
                pass

Очистка полей и интерфейс tkinter.

def clearn():
        txt_0.delete(1.0, END)
        txt_1.delete(1.0, END)
        txt.delete(1.0, END)
import tkinter as tk    
from tkinter import *
root = tk.Tk()       
main_menu = Menu(root)
root.config(menu=main_menu)
file_menu = Menu(main_menu)
main_menu.add_cascade(label="Орфография", menu=file_menu)
file_menu.add_command(label="Проверка блока текста", command=tokenise)
file_menu.add_command(label="Очистка всех полей", command=clearn)
file_menu.add_command(label="Выход", command=root.destroy)
lab = tk.Label(root, text="Выбирите язык", font="Arial 12")
l = tk.Listbox(root,takefocus=True, width=6,height=5,font="Arial 12")
txt = tk.Text(root, width=64,height=5,font="Arial 12",wrap=WORD)
txt_0 = tk.Text(root, width=64,height=1,font="Arial 12",wrap=WORD)
txt_1 = tk.Text(root, width=64,height=5,font="Arial 12",wrap=WORD)
but = tk.Button(root,text="Проверить слово",command=pravopus)
lab.grid(row=0, column=0)
txt_1.grid(row=1, column=0)
txt_0.grid(row=2, column=0)
txt.grid(row=3, column=0)
l.grid(row=3, column=1)
but.grid(row=4, column=0)
l.insert(END,'en_AU', 'en_GB', 'en_US', 'de_DE', 'fr_FR', 'ru_RU', 'uk_UA')    
l.bind("<<ListboxSelect>>", get)
root.tk.mainloop()

Работа программы

Пример работы с русскими словами.

Пример работы с английским предложением.

Пример работы с немецким предложением.

1. Python проверка орфографии (windows, linux) — PyEnchant

I’m fairly new to Python and NLTK. I am busy with an application that can perform spell checks (replaces an incorrectly spelled word with the correct one).
I’m currently using the Enchant library on Python 2.7, PyEnchant and the NLTK library. The code below is a class that handles the correction/replacement.

from nltk.metrics import edit_distance

class SpellingReplacer:
    def __init__(self, dict_name='en_GB', max_dist=2):
        self.spell_dict = enchant.Dict(dict_name)
        self.max_dist = 2

    def replace(self, word):
        if self.spell_dict.check(word):
            return word
        suggestions = self.spell_dict.suggest(word)

        if suggestions and edit_distance(word, suggestions[0]) <= self.max_dist:
            return suggestions[0]
        else:
            return word

I have written a function that takes in a list of words and executes replace() on each word and then returns a list of those words, but spelled correctly.

def spell_check(word_list):
    checked_list = []
    for item in word_list:
        replacer = SpellingReplacer()
        r = replacer.replace(item)
        checked_list.append(r)
    return checked_list

>>> word_list = ['car', 'colour']
>>> spell_check(words)
['car', 'color']

Now, I don’t really like this because it isn’t very accurate and I’m looking for a way to achieve spelling checks and replacements on words. I also need something that can pick up spelling mistakes like «caaaar»? Are there better ways to perform spelling checks out there? If so, what are they? How does Google do it? Because their spelling suggester is very good.

Any suggestions?

User's user avatar

User

1,14810 silver badges29 bronze badges

asked Dec 18, 2012 at 7:18

Mike Barnes's user avatar

Mike BarnesMike Barnes

4,11718 gold badges39 silver badges64 bronze badges

You can use the autocorrect lib to spell check in python.
Example Usage:

from autocorrect import Speller

spell = Speller(lang='en')

print(spell('caaaar'))
print(spell('mussage'))
print(spell('survice'))
print(spell('hte'))

Result:

caesar
message
service
the

Sunil Garg's user avatar

Sunil Garg

13.8k24 gold badges126 silver badges176 bronze badges

answered Jan 16, 2018 at 11:48

Rakesh's user avatar

5

I’d recommend starting by carefully reading this post by Peter Norvig. (I had to something similar and I found it extremely useful.)

The following function, in particular has the ideas that you now need to make your spell checker more sophisticated: splitting, deleting, transposing, and inserting the irregular words to ‘correct’ them.

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

Note: The above is one snippet from Norvig’s spelling corrector

And the good news is that you can incrementally add to and keep improving your spell-checker.

Hope that helps.

answered Dec 18, 2012 at 17:13

Ram Narasimhan's user avatar

Ram NarasimhanRam Narasimhan

22.2k5 gold badges48 silver badges54 bronze badges

1

The best way for spell checking in python is by: SymSpell, Bk-Tree or Peter Novig’s method.

The fastest one is SymSpell.

This is Method1: Reference link pyspellchecker

This library is based on Peter Norvig’s implementation.

pip install pyspellchecker

from spellchecker import SpellChecker

spell = SpellChecker()

# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])

for word in misspelled:
    # Get the one `most likely` answer
    print(spell.correction(word))

    # Get a list of `likely` options
    print(spell.candidates(word))

Method2: SymSpell Python

pip install -U symspellpy

answered Feb 17, 2019 at 18:24

Shaurya Uppal's user avatar

2

Maybe it is too late, but I am answering for future searches.
TO perform spelling mistake correction, you first need to make sure the word is not absurd or from slang like, caaaar, amazzzing etc. with repeated alphabets. So, we first need to get rid of these alphabets. As we know in English language words usually have a maximum of 2 repeated alphabets, e.g., hello., so we remove the extra repetitions from the words first and then check them for spelling.
For removing the extra alphabets, you can use Regular Expression module in Python.

Once this is done use Pyspellchecker library from Python for correcting spellings.

For implementation visit this link: https://rustyonrampage.github.io/text-mining/2017/11/28/spelling-correction-with-python-and-nltk.html

answered Apr 3, 2019 at 10:10

Rishabh Sahrawat's user avatar

2

Try jamspell — it works pretty well for automatic spelling correction:

import jamspell

corrector = jamspell.TSpellCorrector()
corrector.LoadLangModel('en.bin')

corrector.FixFragment('Some sentnec with error')
# u'Some sentence with error'

corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
# ('sentence', 'senate', 'scented', 'sentinel')

jupiterbjy's user avatar

jupiterbjy

2,6671 gold badge10 silver badges27 bronze badges

answered Aug 28, 2020 at 23:00

Fippo's user avatar

FippoFippo

511 silver badge5 bronze badges

2

IN TERMINAL

pip install gingerit

FOR CODE

from gingerit.gingerit import GingerIt
text = input("Enter text to be corrected")
result = GingerIt().parse(text)
corrections = result['corrections']
correctText = result['result']

print("Correct Text:",correctText)
print()
print("CORRECTIONS")
for d in corrections:
  print("________________")  
  print("Previous:",d['text'])  
  print("Correction:",d['correct'])   
  print("`Definiton`:",d['definition'])
 

answered Mar 28, 2021 at 16:21

pouya barari's user avatar

1

You can also try:

pip install textblob

from textblob import TextBlob
txt="machne learnig"
b = TextBlob(txt)
print("after spell correction: "+str(b.correct()))

after spell correction: machine learning

answered Nov 30, 2021 at 2:47

Mayur Patil's user avatar

Mayur PatilMayur Patil

1392 silver badges5 bronze badges

2

spell corrector->

you need to import a corpus on to your desktop if you store elsewhere change the path in the code i have added a few graphics as well using tkinter and this is only to tackle non word errors!!

def min_edit_dist(word1,word2):
    len_1=len(word1)
    len_2=len(word2)
    x = [[0]*(len_2+1) for _ in range(len_1+1)]#the matrix whose last element ->edit distance
    for i in range(0,len_1+1):  
        #initialization of base case values
        x[i][0]=i
        for j in range(0,len_2+1):
            x[0][j]=j
    for i in range (1,len_1+1):
        for j in range(1,len_2+1):
            if word1[i-1]==word2[j-1]:
                x[i][j] = x[i-1][j-1]
            else :
                x[i][j]= min(x[i][j-1],x[i-1][j],x[i-1][j-1])+1
    return x[i][j]
from Tkinter import *


def retrieve_text():
    global word1
    word1=(app_entry.get())
    path="C:Documents and SettingsOwnerDesktopDictionary.txt"
    ffile=open(path,'r')
    lines=ffile.readlines()
    distance_list=[]
    print "Suggestions coming right up count till 10"
    for i in range(0,58109):
        dist=min_edit_dist(word1,lines[i])
        distance_list.append(dist)
    for j in range(0,58109):
        if distance_list[j]<=2:
            print lines[j]
            print" "   
    ffile.close()
if __name__ == "__main__":
    app_win = Tk()
    app_win.title("spell")
    app_label = Label(app_win, text="Enter the incorrect word")
    app_label.pack()
    app_entry = Entry(app_win)
    app_entry.pack()
    app_button = Button(app_win, text="Get Suggestions", command=retrieve_text)
    app_button.pack()
    # Initialize GUI loop
    app_win.mainloop()

pyspellchecker is the one of the best solutions for this problem. pyspellchecker library is based on Peter Norvig’s blog post.
It uses a Levenshtein Distance algorithm to find permutations within an edit distance of 2 from the original word.
There are two ways to install this library. The official document highly recommends using the pipev package.

  • install using pip
pip install pyspellchecker
  • install from source
git clone https://github.com/barrust/pyspellchecker.git
cd pyspellchecker
python setup.py install

the following code is the example provided from the documentation

from spellchecker import SpellChecker

spell = SpellChecker()

# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])

for word in misspelled:
    # Get the one `most likely` answer
    print(spell.correction(word))

    # Get a list of `likely` options
    print(spell.candidates(word))

answered Sep 10, 2020 at 15:30

Sabesan's user avatar

SabesanSabesan

5941 gold badge9 silver badges16 bronze badges

from autocorrect import spell
for this you need to install, prefer anaconda and it only works for words, not sentences so that’s a limitation u gonna face.

from autocorrect import spell
print(spell('intrerpreter'))
# output: interpreter

Ketan's user avatar

Ketan

131 silver badge3 bronze badges

answered Dec 28, 2018 at 11:17

Saurabh Tripathi's user avatar

1

pip install scuse

from scuse import scuse

obj = scuse()

checkedspell = obj.wordf("spelling you want to check")

print(checkedspell)

answered Sep 7, 2022 at 7:05

mrithul e's user avatar

answered Mar 12, 2020 at 14:02

Nabin's user avatar

NabinNabin

11k8 gold badges64 silver badges98 bronze badges

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

Использование библиотеки textblob

Во-первых, вам нужно установить библиотечный текстовый блок с помощью команды pip в командной строке.

 pip install textblob

You can also install this library in Jupyter Notebook as: 
 

Python3

import sys

!{sys.executable} - m pip install textblob

Программа для проверки орфографии —

Python3

from textblob import TextBlob

a = "cmputr"          

print("original text: "+str(a))

b = TextBlob(a)

print("corrected text: "+str(b.correct()))

Выход:

 исходный текст: cmputr
исправленный текст: компьютер


Использование библиотеки pyspellchecker

Вы можете установить эту библиотеку, как показано ниже:
Используя pip:

 pip install pyspellchecker


In Jupyter Notebook: 
 

Python3

import sys

!{sys.executable} - m pip install pyspellchecker

  
Spelling Checker program using pyspellchecker – 
 

Python3

from spellchecker import SpellChecker

spell = SpellChecker()

misspelled = spell.unknown(["cmputr", "watr", "study", "wrte"])

for word in misspelled:

    print(spell.correction(word))

    print(spell.candidates(word))

Выход:

computer
{"caput", "caputs", "compute", "computor", "impute", "computer"}
water
{"water", "watt", "warr", "wart", "war", "wath", "wat"}
write
{"wroe", "arte", "wre", "rte", "wrote", "write"}


Использование JamSpell

Для достижения наилучшего качества при исправлении правописания словарных методов недостаточно. Вы должны учитывать слово «окружение». JamSpell — это библиотека проверки орфографии на Python, основанная на языковой модели. Он вносит разные поправки для другого контекста.

1) Установить swig3

 apt-get install swig3.0 # для Linux
brew install swig @ 3 # для Mac

2) Установите jamspell

 pip install jamspell

3) Download a language model for your language

Python3

corrector = jamspell.TSpellCorrector()

corrector.LoadLangModel("Downloads/en_model.bin")

print(corrector.FixFragment("I am the begt spell cherken!"))

print(corrector.GetCandidates(["i", "am", "the", "begt", "spell", "cherken"], 3))

print(corrector.GetCandidates(["i", "am", "the", "begt", "spell", "cherken"], 5))

Выход:

 «Я лучший специалист по проверке правописания!»
(u'best ', u'beat', u'belt ', u'bet', u'bent ')
(u'checker ', u'chicken', u'checked ', u'wherein', u'связный ', ...)

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение — базовый уровень.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Исправление бух ошибки после сдачи отчетности
  • Исправление арифметической ошибки влияющей на права третьих лиц допускается