import java.util.*;
import java.io.*;
import java.util.regex.*;
public class CountWords
{
private File file;
private ArrayList<Word> words;
public CountWords(String fileName)
{
this(new File(fileName));
}
public CountWords(File file)
{
this.file = file;
words = new ArrayList<Word>();
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
String str = "";
String line;
while((line = in.readLine())!= null)
str += line + " ";
str = str.toLowerCase(); // Word matching is case insensitive
in.close();
Pattern wordPattern = Pattern.compile("[a-z-]+");
Matcher matcher = wordPattern.matcher(str);
while(matcher.find())
{
String word = str.substring(matcher.start(), matcher.end());
if(!(word.equals("null") || word.equals("-"))) // If the word is not "-" or "null"
{
int index = inArray(word);
if(index != -1) // If the current word is in the words ArrayList
words.get(index).addCount();
else // Otherwise add new word
words.add(new Word(word));
}
}
Collections.sort(words);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public int numWords()
{
int sum = 0;
for(int i = 0; i < words.size(); i++)
sum += words.get(i).getCount();
return sum;
}
public void printTopWords(int n)
{
System.out.println("Unique Words: " + words.size());
System.out.println("Word Count: " + numWords());
for(int i = 0; i < n; i++)
System.out.println(i + ". " + words.get(i).getWord() + " - " + words.get(i).getCount());
}
public void printTopWords()
{
printTopWords(20);
}
private int inArray(String word)
{
for(int i = 0; i < words.size(); i++)
if(word.equals(words.get(i).getWord()))
return i;
return -1;
}
}