Skip to content

Instantly share code, notes, and snippets.

@atdaemon
Created November 15, 2015 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atdaemon/9f59ad886c35024bdd28 to your computer and use it in GitHub Desktop.
Save atdaemon/9f59ad886c35024bdd28 to your computer and use it in GitHub Desktop.
"""
Print dict words that are closest to given word, upto a set distance (of 2),
sorted acc to increasing distance
Levenshtein module installed using -
pip install python-levenshtein
"""
from Levenshtein import distance
import os
def read_dict() :
with open('/usr/share/dict/words','r') as f :
for line in f :
yield str(line).strip()
inp = str(raw_input('Enter a word : '))
wordlist = read_dict()
matches = []
for word in wordlist :
dist = distance(inp,word)
if dist < 3 :
matches.append((dist,word))
print os.linesep.join(map(str,sorted(matches)))
"""
sample output -
Enter a word : checker
(0, 'checker')
(1, 'checked')
(1, 'checkers')
(2, 'Becker')
(2, 'Decker')
(2, 'cheaper')
(2, 'cheater')
(2, 'check')
(2, "check's")
(2, "checker's")
(2, 'checkered')
(2, 'checks')
(2, 'checkup')
(2, 'cheeked')
(2, 'cheekier')
(2, 'cheer')
(2, 'chewer')
(2, 'chewier')
(2, 'chicer')
(2, 'chicken')
(2, 'chocked')
(2, 'choker')
(2, 'chucked')
(2, 'cracker')
(2, 'hacker')
(2, 'heckler')
(2, 'shocker')
(2, 'thicker')
(2, 'wrecker')
Enter a word : job
(0, 'job')
(1, 'Bob')
(1, 'Job')
(1, 'Rob')
(1, 'bob')
(1, 'cob')
(1, 'fob')
(1, 'gob')
(1, 'hob')
(1, 'jab')
(1, 'jib')
(1, 'jobs')
(1, 'jog')
(1, 'jot')
(1, 'joy')
(1, 'lob')
(1, 'mob')
(1, 'rob')
(1, 'sob')
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment