ivolff

4Words

Oct 16th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. import java.util.*;
  2. import java.nio.file.*;
  3. import java.io.*;
  4.  
  5. public class WordStatWords {
  6.     public static void main(String[] args) {
  7.         Map<String, Integer> words = new LinkedHashMap<String, Integer>();
  8.         String word;
  9.         int index;
  10.  
  11.         try {
  12.             for (String line : Files.readAllLines(Paths.get(args[0]))) {
  13.                 index = 0;
  14.  
  15.                 for (int i = 0; i < line.length(); i++) {
  16.                     char c = line.charAt(i);
  17.  
  18.                     if (!(Character.isLetter(c) ||
  19.                         Character.getType(c) == Character.DASH_PUNCTUATION ||
  20.                         c == '\'')) {
  21.                         if (index == i) {
  22.                             index++;
  23.                         } else {
  24.                             word = line.substring(index, i).toLowerCase();
  25.  
  26.                             if (words.containsKey(word)) {
  27.                                 words.put(word, words.get(word) + 1);
  28.                             } else {
  29.                                 words.put(word, 1);
  30.                             }
  31.  
  32.                             index = i + 1;
  33.                         }
  34.                     }
  35.                 }
  36.  
  37.                 if (index != line.length()) {
  38.                     word = line.substring(index).toLowerCase();
  39.  
  40.                     if (words.containsKey(word)) {
  41.                         words.put(word, words.get(word) + 1);
  42.                     } else {
  43.                         words.put(word, 1);
  44.                     }
  45.                 }
  46.             }
  47.  
  48.             PrintWriter writer = new PrintWriter(args[1], "utf8");
  49.  
  50.             try {
  51.                 words.entrySet().stream()
  52.                     .sorted(Map.Entry.comparingByKey())
  53.                     .forEach(entry -> writer.println(entry.getKey() + " " + entry.getValue()));
  54.             } finally {
  55.                 writer.close();
  56.             }
  57.         } catch (IOException e) {
  58.             e.printStackTrace();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment