Skip to content

Commit

Permalink
addition of support for a distance of 1 (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrjamesriley authored and barrust committed Oct 3, 2018
1 parent 2bdb305 commit b5f38d9
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
10 changes: 7 additions & 3 deletions spellchecker/spellchecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ class SpellChecker(object):
for no dictionary. Supported languages are `en`, `es`, `de`, and \
`fr`. Defaults to `en`
local_dictionary (str): The path to a locally stored word \
frequency dictionary '''
frequency dictionary
distance (int): The edit distance to use. Defaults to 2'''

def __init__(self, language='en', local_dictionary=None):

def __init__(self, language='en', local_dictionary=None, distance=2):
self._distance = distance
self._word_frequency = WordFrequency()
if local_dictionary:
self._word_frequency.load_dictionary(local_dictionary)
Expand Down Expand Up @@ -95,8 +98,9 @@ def candidates(self, word):
word (str): The word for which to calculate candidate spellings
Returns:
set: The set of words that are possible candidates '''

return (self.known([word]) or self.known(self.edit_distance_1(word)) or
self.known(self.edit_distance_2(word)) or {word})
(self._distance == 2 and self.known(self.edit_distance_2(word))) or {word})

def known(self, words):
''' The subset of `words` that appear in the dictionary of words
Expand Down
3 changes: 2 additions & 1 deletion tests/resources/small_dictionary.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"a": 1,
"b": 2,
"apple": 45
"apple": 45,
"bike": 60
}
8 changes: 7 additions & 1 deletion tests/spellchecker_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from spellchecker import SpellChecker


class TestSpellChecker(unittest.TestCase):
''' test the spell checker class '''

Expand Down Expand Up @@ -117,6 +116,13 @@ def test_load_external_dictionary(self):
self.assertEqual(spell['a'], 1)
self.assertTrue('apple' in spell)

def test_edit_distance_one(self):
''' test a case where edit distance must be one '''
here = os.path.dirname(__file__)
filepath = '{}/resources/small_dictionary.json'.format(here)
spell = SpellChecker(language=None, local_dictionary=filepath, distance=1)
self.assertEqual(spell.candidates('hike'), {'bike'})

def test_edit_distance_two(self):
''' test a case where edit distance must be two '''
here = os.path.dirname(__file__)
Expand Down

0 comments on commit b5f38d9

Please sign in to comment.