Write a java program to implement a spell-checker class that reading from two in
ID: 3762907 • Letter: W
Question
Write a java program to implement a spell-checker class that reading from two input files. The first file is a dictionary containing one word per line. The program should read the dictionary and insert the words into a hash table. After reading the dictionary, it will read a list of words from a second file. The goal of the spell- checker is to determine the misspelled words in the second file by looking each word up in the dictionary. You should output each misspelled word, the line numbers in which it occurs, and a list of possible corrections.
Possible Corrections: If the word you are looking for is not in the dictionary, assume that it is misspelled. To suggest corrections, for each misspelled word, list any words in the dictionary that are obtainable by any of the following rules.
• Change one letter: For example, if the misspelled word is “kest”, try all possibilities of changing one character at a time, and look the modified word up in the dictionary. The possibilities will be “aest”, “best”,...,”zest”, “kast”,...,”kzst”, etc.
• Exchange adjacent letters: For example, if the misspelled word is “ebst”, try “best”, esbt” and “ebts”.
• Remove one letter: For example, if the misspelled word is “tbird”, try all possibilities of removing one letter at a time, and look the modified word up in the dictionary, which are: “bird”, “tird”, “tbrd”, and “tbir”.
Note that, you have to try all possibilities, but only the ones that are actually found in the dictionary are possible corrections to be suggested.
Explanation / Answer
import java.io.*; import java.util.HashSet; import java.util.Set; public class JavaSpellChecker { private static final File DICTIONARY_WORDS = new File("/usr/share/dict/words"); boolean checkSpelling(String input) throws IOException { Set words = readDictionary(); for (String word : input.toLowerCase().split(" ")) { if (!words.contains(word)) { System.out.println(word + " is not in the dictionary"); return false; } } return true; } private Set readDictionary() throws IOException { Set words = new HashSet(); words.add("java"); // add java to dictionary InputStream stream = new FileInputStream(DICTIONARY_WORDS); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String word; while ((word = reader.readLine()) != null) { words.add(word); } } finally { stream.close(); } return words; } public static void main(String[] args) throws IOException { String defaultInput = "Java is an island"; boolean valid = new JavaSpellChecker().checkSpelling(args.length > 0 ? args[0] : defaultInput); System.out.println("Is the text valid? " + valid); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.