PageRenderTime 21ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

/src/spelling/corrector/DefaultSpellingCorrector.java

https://github.com/juliengrenier/java-spelling-corrector
Java | 62 lines | 51 code | 11 blank | 0 comment | 8 complexity | 36f33f47b95f5e7ba3ccc9f19d620018 MD5 | raw file
  1. package spelling.corrector;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import java.util.Locale;
  7. import spelling.dictionary.Dictionary;
  8. public class DefaultSpellingCorrector implements SpellingCorrector {
  9. private final Dictionary dictionnary;
  10. private final SpellingCorrectorHelper helper;
  11. protected DefaultSpellingCorrector(SpellingCorrectorHelper helper){
  12. this(helper,Locale.ENGLISH);
  13. }
  14. protected DefaultSpellingCorrector(SpellingCorrectorHelper helper,Locale locale){
  15. this.helper = helper;
  16. this.dictionnary = Dictionary.getDictionnary(locale);
  17. }
  18. public String correct(final String word){
  19. String correction = "";
  20. if(word == null || word.equals("")){
  21. return correction;
  22. }
  23. Collection<String> candidates = getCandidates(word.toLowerCase());
  24. int max = 0;
  25. for(String candidate : candidates){
  26. if(dictionnary.getOccurences(candidate) > max){
  27. correction = candidate;
  28. }
  29. }
  30. return correction;
  31. }
  32. public Collection<String> getCandidates(final String word){
  33. List<String> words = new ArrayList<String>();
  34. words.add(word);
  35. Collection<String> knownWords = dictionnary.known(words);
  36. if(knownWords.size() >0){
  37. return knownWords;
  38. }
  39. Collection<String> alternatives = helper.getFirstDegreeAlternatives(word);
  40. knownWords = dictionnary.known(alternatives);
  41. if(knownWords.size() > 0){
  42. return knownWords;
  43. }
  44. Collection<String> secondDegreeAlternatives = helper.getSecondDegreeAlternatives(alternatives);
  45. knownWords = dictionnary.known(secondDegreeAlternatives);
  46. if(knownWords.size() > 0){
  47. return knownWords;
  48. }
  49. return Collections.unmodifiableCollection(words);
  50. }
  51. }