/****************************************************************************** * This program implements a spell checker. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.pureprogrammer.Utils; public class SpellChecker { static Map DICTIONARY = new HashMap<>(); static void readDictionaryFile(String filespec) throws IOException { BufferedReader ifh = Files.newBufferedReader(FileSystems.getDefault().getPath(filespec), Charset.forName("UTF-8")); String line; while ((line = ifh.readLine()) != null) { DICTIONARY.put(line.toLowerCase(), true); } try {ifh.close();} catch (IOException ex) {}; } static void spellcheckFile(String filespec) throws IOException { BufferedReader ifh = Files.newBufferedReader(FileSystems.getDefault().getPath(filespec), Charset.forName("UTF-8")); String line; Map misspelledWords = new HashMap<>(); while ((line = ifh.readLine()) != null) { List matches = Utils.findAll(Pattern.compile("\\w+"), line); if (Utils.defined(matches)) { for (String s : matches) { final String SLOWER = s.toLowerCase(); if (!DICTIONARY.containsKey(SLOWER)) { misspelledWords.put(SLOWER, true); } } } } final List sortedkeys = Utils.sort(List.copyOf(misspelledWords.keySet())); for (String s : sortedkeys) { System.out.println(s); } try {ifh.close();} catch (IOException ex) {}; } public static void main(String[] args) { if (args.length != 2) { System.out.println(Utils.join("", "Syntax: ", "SpellChecker", " {dictionary} {filename}")); System.exit(1); } String dictionaryFile = args[0]; String filename = args[1]; try { readDictionaryFile(dictionaryFile); spellcheckFile(filename); } catch (IOException ex) { System.out.println(Utils.join("", "Error: ", Utils.exceptionMessage(ex))); } } }