forked from animeshsrivastava24/PythonBeginnerSCript
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspellCheck.py
More file actions
Latest commit
40 lines (31 loc) · 1.47 KB
/
Copy pathspellCheck.py
File metadata and controls
40 lines (31 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
importre
fromcollectionsimportCounter
defwords(text): returnre.findall(r'\w+', text.lower())
WORDS=Counter(words(open('words.txt').read()))
defP(word, N=sum(WORDS.values())):
"Probability of `word`."
#print(WORDS[word])
returnWORDS[word] /N
defcorrection(word):
"Most probable spelling correction for word."
#print(candidates(word))
returnmax(candidates(word), key=P)
defcandidates(word):
"Generate possible spelling corrections for word."
return (known([word]) orknown(edits1(word)) orknown(edits2(word)) or [word])
defknown(words):
"The subset of `words` that appear in the dictionary of WORDS."
returnset(wforwinwordsifwinWORDS)
defedits1(word):
"All edits that are one edit away from `word`."
letters='abcdefghijklmnopqrstuvwxyz'
splits= [(word[:i], word[i:]) foriinrange(len(word) +1)]
deletes= [L+R[1:] forL, RinsplitsifR]
transposes= [L+R[1] +R[0] +R[2:] forL, Rinsplitsiflen(R)>1]
replaces= [L+c+R[1:] forL, RinsplitsifRforcinletters]
inserts= [L+c+RforL, Rinsplitsforcinletters]
returnset(deletes+transposes+replaces+inserts)
defedits2(word):
"All edits that are two edits away from `word`."
return (e2fore1inedits1(word) fore2inedits1(e1))
print("correction for 'pythob' = ", correction("pythob")) #prints 'python'