venerdì 25 giugno 2010

How to suggest alternate spellings/3 [ENG]

The scenario is well defined already:

  1. the user types in a string in a field restricted to a dictionary
  2. we know how to calculate the edit distance between every string in our dictionary and the user input
  3. so we bundle up a word with its score and define a sorting rule
Time to wrap it up:

public class SpellSuggester
{
    
    private List<Word> dictionary;
    
  
    public SpellSuggester(...)
    {
       // load the dictionary however you prefer
    }
    
    public List<Word> getSimilarWords(String wordToSearch, int limit)
    {
        // 1. compute the score
        for (Word word : dictionary)
        {
            word.setScore(spellChecking.levenshteinDistance(word.getWord(), wordToSearch));
        }
        
        // 2. sort
        Collections.sort(dictionary, new WordComparator());

        // 3. extract the first 'limit' entries (if limit == 0 returns the whole list)
        if (limit<=0)
        {
            return dictionary;
        }
        else
        {
            return dictionary.subList(0, limit);
        }
    }
    
}

Pretty simple isn't it?

Nessun commento: