import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * @author gtowell * Written: Jan 29, 2020 * Modified: Sep 16, 2020 * * A small class that counts the number of uses of each word in a file. * This illustrates use of maps as opposed to ArrayList. Also key value pairs */ public class WordCounterMap { /** An map holding all of the Word and Count objects */ //private ArrayList counts = new ArrayList<>(); private Map206 counts = new Map206<>(); /** * Does most of the heavy lifting. Reads a file and fills in the counts * arraylist appropriately * * @param filename the name of the file to be read. */ public void countFileComplete(String filename) { try (BufferedReader br = new BufferedReader(new FileReader(filename));) { String line; while (null != (line = br.readLine())) { // read line and test if there is a line to read line = line.toLowerCase().replace(".", "").replace(",", "").replace("?", "").replace("!", "").replace("-", " "); String[] ss = line.split("\\s+"); // split the line by spaces for (String token : ss) { // take the token i.e. word, lower case it, then get rid of punctuation //token = token.toLowerCase().replace(".", "").replace(",", "").replace("?", "").replace("!", ""); if (token.length() > 0) { int tokencount = 0; if (counts.containsKey(token)) { tokencount=counts.get(token); } counts.put(token, tokencount+1); } } } } catch (FileNotFoundException e) { System.err.println("Error in opening the file:" + filename); System.exit(1); } catch (IOException ioe) { System.err.println("Error reading file " + ioe); System.exit(1); } } public void countFile(String filename) { try (BufferedReader br = new BufferedReader(new FileReader(filename));) { while (br.ready()) { String line = br.readLine(); String[] words= line.split("\\s+"); for (String w : words) { if (counts.containsKey(w)) { counts.put(w, counts.get(w)+1); } else { counts.put(w, 1); } } } } catch (Exception ioe) { System.err.println("Rread problemn " + ioe); } } public String toString() { // StringBuffer is a modifiable string. If you are changing a string a lot, it // is much more efficient. StringBuffer sb = new StringBuffer(); for (String key : counts.keySet()) { sb.append(key + " " + counts.get(key)); sb.append("\n"); } sb.append("Distinct words: " + counts.size()); return sb.toString(); } public static void main(String[] args) { WordCounterMap wc = new WordCounterMap(); wc.countFile("ham1.txt"); System.out.println(wc); } }