I am a bit stuck on how to sort the frequency of a word from any text file input. I was able to code the frequency of each code but I'm not sure how to sort them out from the most frequently occurring word.
This is what I have for the frequency.
For example. I have a file text that read.
This is a test run.
I come with no wrapping or pretty pink bows.
I am who I am from my head to my toes.
I tend to get loud when speaking my mind.
Even a little crazy some of the time.
I. am. who. I. am.
the output with this code is.
2 a
2 am
2 am.
1 bows.
1 come
1 crazy
1 even
1 from
1 get
1 head
4 i
2 i.
1 is
1 little
1 loud
1 mind.
3 my
1 no
1 of
1 or
1 pink
1 pretty
1 run.
1 some
1 speaking
1 tend
1 test
1 the
1 this
1 time.
2 to
1 toes.
1 when
1 who
1 who.
1 with
1 wrapping
I was also wondering how can I ignore the period because some same words are being overcounted because of the period.
Scanner input;
try {
input = new Scanner(file);
Map<String, Integer> wordCounts = new TreeMap<String, Integer>();
while (input.hasNext()) {
String next = input.next().toLowerCase();
if (!wordCounts.containsKey(next)) {
wordCounts.put(next, 1);
} else {
wordCounts.put(next, wordCounts.get(next) + 1);
}
}
// report frequencies
for (String word : wordCounts.keySet()) {
int count = wordCounts.get(word);
System.out.println(count + "\t" + word);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}