PageRenderTime 13ms CodeModel.GetById 0ms app.highlight 12ms RepoModel.GetById 0ms app.codeStats 0ms

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