Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.HashMap;
- import java.util.Scanner;
- public class HashMap_WordsCounting {
- public static void main(String[] args ) throws IOException {
- Scanner words = new Scanner(new File("C:/Users/Petra/IdeaProjects/first/src/words.txt")); //Hash-Map with search words
- HashMap<String, Integer> countingWords = new HashMap<>();
- while (words.hasNextLine()) {
- countingWords.put(words.nextLine().toLowerCase(), 0);
- }
- words.close();
- Scanner text = new Scanner(new File("C:/Users/Petra/IdeaProjects/first/src/sample.txt")); //Crawl all words in the file
- while (text.hasNext()) {
- String word = text.next().toLowerCase();
- // In case after word there is simbol
- word = word.replaceAll("[^а-яАZ0-9]", "");
- if (countingWords.containsKey(word)) {
- int count = countingWords.get(word) + 1;
- countingWords.put(word, count);
- }
- }
- //Save the results in file
- File result = new File("result.txt");
- FileWriter fw = new FileWriter(result);
- PrintWriter printw = new PrintWriter(fw);
- printw.write("Намерени съвпадения: \n");
- printw.write(String.valueOf(countingWords));
- printw.close();
- System.out.println("Намерени съвпадения: \n"+countingWords);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement