Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package WordCount;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.HashMap;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) throws IOException {
- Scanner words = new Scanner(new File("D:/Code/DataStructures/src/WordCount/words.txt")); //Речник с търсените думи
- HashMap<String, Integer> countWords = new HashMap<>();
- while (words.hasNextLine()) {
- countWords.put(words.nextLine().toLowerCase(), 0);
- }
- words.close();
- Scanner text = new Scanner(new File("D:/Code/DataStructures/src/WordCount/sampleText.txt")); //обхождане на всички думи файла
- while (text.hasNext()) {
- String word = text.next().toLowerCase();
- // В случай, че след думата има символ(запетая или точка)
- word = word.replaceAll("[^а-яАZ0-9]", "");
- if (countWords.containsKey(word)) {
- int count = countWords.get(word) + 1;
- countWords.put(word, count);
- }
- }
- //Запазване на резултатите във файл
- File result = new File("result.txt");
- FileWriter fw = new FileWriter(result);
- PrintWriter pw = new PrintWriter(fw);
- pw.write("Намерени съвпадения: \n");
- pw.write(String.valueOf(countWords));
- pw.close();
- System.out.println("Намерени съвпадения: \n"+countWords);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment