Counting the occurrences of words in a text file Rewrite Listing 22.12 in the le
ID: 3863525 • Letter: C
Question
Counting the occurrences of words in a text file
Rewrite Listing 22.12 in the lecture power points to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by whitespace, punctuation marks (,;.:?), quotation marks ('"), and parentheses. Count words in case-insensitive fashion (e.g., consider Good and good to be the same word). Don’t count the word if the first character is not a letter. Display the output in alphabetical order of words with each word preceded by its occurrence count.
Case Study: Occurrence of Words LISTING 22.12 Count occurrenceof Worda. java 1 import java .util. 3 public class CountoccurrenceOfwords 4 public static void main(Stringt args) Set text in a string String text Good morning. Have a good class "Have a good visit. Have fun! Create a Tree Map to hold words as key and count as value 10 TreeMapExplanation / Answer
import java.util.*;
import java.io.*;
public class WordCount
{
public static void main(string[] args) throws FileNotFoundException
{
// open the file
Scanner console = new Scanner(System.in);
System.out.print(“What is the name of the text file?”);
String filename = console.nextLine();
Scanner input = new Scanner(new File(filename));
// count occurences
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);
}
}
//get cutoff and report frequencies
System.out.println(“Total words =” + wordCounts.size());
System.out.println(“Minimum number of occurences for printing?”);
int min = console.nextInt();
for(String word : wordCounts.ketSet())
{
int count = wordCounts.get(word);
if(count >= min)
System.out.println(count + “ ” + word);
}
}
}