(Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the
ID: 3587142 • Letter: #
Question
(Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words *21.8 are delimited by whitespace characters, punctuation marks G,.:?), quotation marks ('"), and parentheses. Count words in case-insensitive fashion (e.g., con- sider Good and good to be the same word). The words must start with a letter. Display the output in alphabetical order of words, with each word preceded by ts occurrence count.Explanation / Answer
package syemmetric;
import java.io.File;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class CounterWordsFile {
public static void main(String[] args) {
String inputfilename = args[0];
TreeMap<String, Integer> treeMap = new TreeMap<String,
Integer>();
try {
Scanner input = new Scanner(new File(inputfilename));
while (input.hasNext()) {
String line = input.nextLine();
String[] words = line.split("[ @!~{}\[\]$#^&* .,;?'") (]");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().length() > 0 && words[i].trim().matches("[A—Z|a—z]+")) {
String key = words[i].toLowerCase();
if (treeMap.get(key) != null) {
int count = treeMap.get(key);
count++;
treeMap.put(key, count);
} else {
treeMap.put(key, 1);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
Set<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();
System.out.print(" Total words in the file : ");
for (Map.Entry<String, Integer> entry : entrySet)
System.out.println(entry.getValue() + " " + entry.getKey());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.