Advertisement
panaewboi

320feb28WordFrequency

Feb 27th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1.  
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.util.Collection;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.Scanner;
  8. import java.util.StringTokenizer;
  9.  
  10. public class WordFrequency {
  11.     private Map<String, WordCounter> words;
  12.    
  13.     public WordFrequency(){
  14.         this(16);
  15.     }
  16.    
  17.     public WordFrequency(int capacity){
  18.         words = new HashMap((int)(capacity*1.25));
  19.     }
  20.    
  21.     public void count(String fileName) throws FileNotFoundException{
  22.         File file = new File(fileName);
  23.         Scanner sc = new Scanner(file);
  24.         String line = null;
  25.         String word = null;
  26.        
  27.         while(sc.hasNextLine()){
  28.             line = sc.nextLine();
  29.             StringTokenizer stk = new StringTokenizer(line, ",;:'\".");
  30.            
  31.             while(stk.hasMoreElements()){
  32.                 word = stk.nextToken();
  33.                
  34.                 if(words.get(word) != null){
  35.                     words.get(word).increment();
  36.                 }else{
  37.                     words.put(word, new WordCounter(word));
  38.                 }
  39.             }
  40.            
  41.         }
  42.        
  43.             sc.close();
  44.     }
  45.  
  46.     @Override
  47.     public String toString() {
  48.         StringBuilder stb = new StringBuilder(15*words.size());
  49.         for(WordCounter wc : words.values()){
  50.             stb.append(String.format("%-10s %2d \n" , wc.getWord(), wc.getCount()));
  51.         }
  52.         return stb.toString();
  53.     }
  54.    
  55.     public Collection<WordCounter> getFrequency(){
  56.         return words.values();
  57.     }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement