Created
May 21, 2012 09:35
-
-
Save Mezzle/2761504 to your computer and use it in GitHub Desktop.
Spell Checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from random import choice | |
class Words: | |
list = {} | |
loaded = False | |
def load(self): | |
f = open('/usr/share/dict/words', 'r') | |
for line in f: | |
line = line.replace("\n", '') | |
hsh = self.getHash(line) | |
if self.list.has_key(hsh): | |
self.list[hsh].append(line) | |
else: | |
self.list[hsh] = [line] | |
f.close() | |
self.loaded = True | |
def getHash(self, word): | |
lower_string = word.lower() | |
cleaned_string = re.sub(r'([^a-z])', r'', lower_string) | |
for letter in ['a','e','i','o','u']: | |
cleaned_string = cleaned_string.replace(letter, '#') | |
parsed_string = re.sub(r'([a-z#])\1+', r'\1', cleaned_string) | |
return parsed_string | |
def check(self, word): | |
if not self.loaded: | |
self.load() | |
if self.list.has_key(self.getHash(word)): | |
print choice(self.list[self.getHash(word)]) | |
else: | |
print 'NO SUGGESTION' | |
def prompt(self): | |
while True: | |
try: | |
line = raw_input('> ') | |
except EOFError: | |
break | |
if not line.strip() == '': | |
yield line | |
def fromStdIn(self): | |
for word in self.prompt(): | |
self.check(word) | |
if __name__ == "__main__": | |
w = Words() | |
w.fromStdIn() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment