Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- import java.util.StringTokenizer;
- public class WordFrequency {
- private Map<String, WordCounter> words;
- public WordFrequency(){
- this(16);
- }
- public WordFrequency(int capacity){
- words = new HashMap((int)(capacity*1.25));
- }
- public void count(String fileName) throws FileNotFoundException{
- File file = new File(fileName);
- Scanner sc = new Scanner(file);
- String line = null;
- String word = null;
- while(sc.hasNextLine()){
- line = sc.nextLine();
- StringTokenizer stk = new StringTokenizer(line, ",;:'\".");
- while(stk.hasMoreElements()){
- word = stk.nextToken();
- if(words.get(word) != null){
- words.get(word).increment();
- }else{
- words.put(word, new WordCounter(word));
- }
- }
- }
- sc.close();
- }
- @Override
- public String toString() {
- StringBuilder stb = new StringBuilder(15*words.size());
- for(WordCounter wc : words.values()){
- stb.append(String.format("%-10s %2d \n" , wc.getWord(), wc.getCount()));
- }
- return stb.toString();
- }
- public Collection<WordCounter> getFrequency(){
- return words.values();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement