Find the most repeated word in a text file with Java

Configurare noua (How To)

Situatie

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.util.ArrayList;
  4. public class MostRepeatedWord {
  5.     public static void main(String[] args) throws Exception {
  6.         String line, word = “”;
  7.         int count = 0, maxCount = 0;
  8.         ArrayList<String> words = new ArrayList<String>();
  9.         //Opens file in read mode  
  10.         FileReader file = new FileReader(“data1.txt “);
  11.         BufferedReader br = new BufferedReader(file);
  12.         //Reads each line  
  13.         while((line = br.readLine()) != null) {
  14.             String string[] = line.toLowerCase().split(“([,.\\s]+) “);
  15.             //Adding all words generated in previous step into words  
  16.             for(String s : string){
  17.                 words.add(s);
  18.             }
  19.         }
  20.         //Determine the most repeated word in a file  
  21.         for(int i = 0; i < words.size(); i++){
  22.             count = 1;
  23.             //Count each word in the file and store it in variable count  
  24.             for(int j = i+1; j < words.size(); j++){
  25.                 if(words.get(i).equals(words.get(j))){
  26.                     count++;
  27.                 }
  28.             }
  29.             //If maxCount is less than count then store value of count in maxCount   
  30.             //and corresponding word to variable word  
  31.             if(count > maxCount){
  32.                 maxCount = count;
  33.                 word = words.get(i);
  34.             }
  35.         }
  36.         System.out.println(“Most repeated word: “ + word);
  37.         br.close();
  38.     }
  39. }

Output:

Most repeated word: word

Solutie

Tip solutie

Permanent

Voteaza

(8 din 17 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?