Advertisement
Petra_Abrasheva_185

WordsCounting_HashMap

Apr 25th, 2021
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.HashMap;
  3. import java.util.Scanner;
  4. public class HashMap_WordsCounting {
  5.     public static void main(String[] args ) throws IOException {
  6.         Scanner words = new Scanner(new File("C:/Users/Petra/IdeaProjects/first/src/words.txt")); //Hash-Map with search words
  7.         HashMap<String, Integer> countingWords = new HashMap<>();
  8.         while (words.hasNextLine()) {
  9.             countingWords.put(words.nextLine().toLowerCase(), 0);
  10.         }
  11.         words.close();
  12.         Scanner text = new Scanner(new File("C:/Users/Petra/IdeaProjects/first/src/sample.txt")); //Crawl all words in the file
  13.         while (text.hasNext()) {
  14.             String word = text.next().toLowerCase();
  15.             // In case after word there is simbol
  16.             word = word.replaceAll("[^а-яАZ0-9]", "");
  17.             if (countingWords.containsKey(word)) {
  18.                 int count = countingWords.get(word) + 1;
  19.                 countingWords.put(word, count);
  20.             }
  21.         }
  22.  
  23.         //Save the results in file
  24.         File result = new File("result.txt");
  25.         FileWriter fw = new FileWriter(result);
  26.         PrintWriter printw = new PrintWriter(fw);
  27.         printw.write("Намерени съвпадения:  \n");
  28.         printw.write(String.valueOf(countingWords));
  29.         printw.close();
  30.  
  31.         System.out.println("Намерени съвпадения:  \n"+countingWords);
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement