Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addition of support for a distance of 1 #17

Merged
merged 1 commit into from
Oct 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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