spell checker with python 3
How it works ?
Main.py is the main file , Spell checker checks the entered word or phrase and if it's wrong it suggests alternative words .
The project on GitHub:
https://github.com/amrelarabi/spell-checker-with-python-3/
For more information you can visit :
http://www.motwr.com/2017/03/python3-spell-checker.html
3. • Since the ordinary Linked List needs to traverse on all nodes till it reaches
the object you are searching for
1
For example :
Finding the 27 in this list
3 15 18 25 27
HEAD
Starting from here==27
123456
4. 6
We see that in Linked List it needs to traverse on
all nodes to reach the specific data [27] because
It exists at the last node.
Which means that Linked List
would traverse on (n) of nodes
for the worst case of running time.
5. • But in Binary Search Tree :
18
To find 27
2515
273
1
ROOT
Starting from here
==27
123
<
<
6. 3
In Binary Search Tree it only traverse on
specific nodes that leads to the specific data [27]
by doing a comparison at each node to determine
the next node.
The Binary Search Tree
would approximately traverse on (log(n)) of nodes
for the worst case of running time.
10. class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
# Returns the number of nodes in the BST.
def length(self):
return self.size
# Determines if the BST contains the given key.
def has_key(self, key):
return self.bstSearch(self.root, key) is not None
# Returns the value associated with the key.
def ValueOf(self, key):
node = self.bstSearch(self.root, key)
# The search process starts from the root.
assert node is not None, "Invalid key." # if node=None, the function stops and message
is printed.
return node.data
BinarySearchTree
(1)
11. BinarySearchTree
(2)
# This method recursively searches the tree for a target key.
# This method returns the address of node or None when:
# (1) the BST is empty or (2) target doesn't exist.
def bstSearch(self, subtree, target):
if subtree is None: # base case
return None
elif target < subtree.key: # target is left of the subtree root.
return self.bstSearch(subtree.left, target)
elif target > subtree.key: # target is right of the subtree root.
return self.bstSearch(subtree.right, target)
else: # base case
return subtree
12. BinarySearchTree(3)
# This method returns the address of the node containing the minimum key.
def bstMinimum(self, subtree):
if subtree is None:
return None # This method returns None when the tree is empty.
else: # When the tree is not empty.
if subtree.left is None:
return subtree
else:
return self.bstMinimum(subtree.left)
# Adds a new entry to BST or replaces the value of an existing key.
def add(self, key, value):
node = self.bstSearch(self.root, key) # Find the node containing the key, if it exists.
if node is not None: # If the key is already in the tree, update its value.
node.value = value
return False
else: # Otherwise, add a new entry.
self.root = self.bstInsert(self.root, key, value) # Starting from the root.
self.size += 1
return True
# This method inserts a new item, recursively.
def bstInsert(self, subtree, key, value):
if subtree is None:
subtree = Node(key, value)
elif key < subtree.key:
subtree.left = self.bstInsert(subtree.left, key, value)
elif key > subtree.key:
subtree.right = self.bstInsert(subtree.right, key, value)
return subtree
13. BinarySearchTree(4)
# Removes the node associated with the given key.
def remove(self, key):
node = self.bstSearch(self.root, key) # The search process starts from the root.
assert node is not None, "Invalid key." # if node=None, the function stops and message is printed.
self.root = self.bstRemove(self.root, key) # The key exists
self.size -= 1
# This method removes an existing item recursively.
def bstRemove(self, subtree, target):
# Search for the item in the tree.
if target < subtree.key:
subtree.left = self.bstRemove(subtree.left, target)
return subtree
elif target > subtree.key:
subtree.right = self.bstRemove(subtree.right, target)
return subtree # We found the node containing the item.
else:
if subtree.left is None and subtree.right is None:
return None
elif subtree.left is None or subtree.right is None:
if subtree.left is not None:
return subtree.left
else:
return subtree.right
else:
successor = self.bstMinimum(subtree.right)
subtree.key = successor.key
subtree.value = successor.value
subtree.right = self.bstRemove(subtree.right, successor.key)
return subtree
17. Translator(1)
class Translator:
"""AVLTree Implementation"""
def __init__(self):
time1 = datetime.now()
print("Loading Database...")
self.__tree = self.__getDictionary()
self.SpellChecker = self.__makeSpellChecker()
time2 = datetime.now()
print("Loaded in {0}rn".format(time2 - time1))
@staticmethod
def __getDictionary():
words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')]
avl = AVLTree()
for word in words:
temp = word.lower().split(':')
avl.insert(temp[0], temp[1])
return avl
@staticmethod
def __makeSpellChecker():
words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')]
english = []
for word in words:
temp = word.lower().split(':')
english.append(temp[0])
return SpellChecker(english)
def hasWord(self, englishWord):
return self.__tree.has_key(englishWord.lower())
18. Translator(2)
def Translate(self, englishWord):
englishWord = englishWord.lower()
trans = self.__tree.ValueOf(englishWord)
result = Result()
if trans is not None:
result.Value = trans
else:
result.Suggesions = self.SpellChecker.GetSuggestions(englishWord)
return result
def TranslateSentense(self, sentense):
words = sentense.split(' ')
FinalOut = ""
output = []
wrong = "Unable to recognize these words, Here are some Suggestions:rn"
w = False
for word in words:
trans = self.Translate(word)
if not trans.Translated():
wrong += word + " => " + str(trans.Suggesions) + "rn"
w = True
output.append(trans.Value if trans.Translated() else word)
FinalOut += " ".join(output) + "rn"
FinalOut += wrong if w else ""
return FinalOut
20. SpellChecker(1)
import math
class SpellChecker:
def __init__(self, tree):
self.wordlist = tree
@staticmethod
def __areInRange(num1, num2, Range=1):
for i in range(Range + 1):
if math.fabs(num1 - num2) == i:
return True
return False
@staticmethod
def __LettersInplace(word, Input):
lettersInplace = 0
for i in range(len(Input)):
if (len(word) > i) and (word[i] == Input[i]):
lettersInplace += 1
return lettersInplace
@staticmethod
def __CommonLetters(word, Input):
commonLetters = 0
Inputs = {}
for i in range(len(Input)):
if (Inputs.get(Input[i], False)):
Inputs[Input[i]] += 1
else:
Inputs[Input[i]] = 1
for key, value in Inputs.items():
if word.count(key) == value:
commonLetters += 1
if (Input[len(Input) - 1] == word[len(word) - 1]):
commonLetters += 1
if (len(Input) == len(word)):
commonLetters += 1
if word[0] == Input[0]:
commonLetters += 1
21. SpellChecker(2)
@staticmethod
def __LettersInRange(word, Input):
lettersInRange = 0
for i in range(len(Input)):
if (len(word) > i) and (Input[i] in word) and SpellChecker.__areInRange(i, Input.index(word[i]) if (word[i] in Input) else -1):
lettersInRange += 1
return lettersInRange
def IsValid(self, Input):
return Input in self.__tree
def GetSuggestions(self, Input, NumOfSuggestions = 5):
arr = []
for word in self.wordlist:
if SpellChecker.__areInRange(len(word), len(Input), 1):
arr.append(word)
dic = {}
for word in arr:
NumOfSimilarities = 0
NumOfSimilarities += SpellChecker.__CommonLetters(str(word), Input)
NumOfSimilarities += SpellChecker.__LettersInplace(str(word), Input)
NumOfSimilarities += SpellChecker.__LettersInRange(str(word), Input)
dic[str(word)] = NumOfSimilarities
Maxes = []
for i in range(NumOfSuggestions):
if len(dic) > 0:
Max = list(dic.keys())[list(dic.values()).index(max(dic.values()))]
Maxes.append(Max)
del dic[str(Max)]
return Maxes