1
+ /*********************************************************************************
2
+ * (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read *
3
+ * the text from a text file. The text file is passed as a command-line argument. *
4
+ * Words are delimited by whitespace characters, punctuation marks (,;.:?), *
5
+ * quotation marks ('"), and parentheses. Count words in case-insensitive fashion *
6
+ * (e.g., consider Good and good to be the same word). The words must start with *
7
+ * a letter. Display the output in alphabetical order of words, with each word *
8
+ * preceded by its occurrence count. *
9
+ *********************************************************************************/
10
+ import java .util .*;
11
+ import java .io .*;
12
+
13
+ public class Exercise_21_08 {
14
+ public static void main (String []args )throws Exception {
15
+ // Check command-line argument length
16
+ if (args .length !=1 ) {
17
+ System .out .println ("Usage: java Exercise_21_08 textFileName" );
18
+ System .exit (1 );
19
+ }
20
+
21
+ // Check if the file exists
22
+ File file =new File (args [0 ]);
23
+ if (!file .exists ()) {
24
+ System .out .println ("The file " +args [0 ] +" does not exists." );
25
+ System .exit (1 );
26
+ }
27
+
28
+ // Create a TreeMap to hold words as key and count as value
29
+ Map <String ,Integer >map =new TreeMap <>();
30
+
31
+ try (// Create an input stream
32
+ Scanner input =new Scanner (file );
33
+ ) {
34
+ while (input .hasNext ()) {
35
+ String []words =input .nextLine ().split ("[\n \t \r \" \' .,;:!?()]" );
36
+ store (map ,words );
37
+ }
38
+ }
39
+
40
+ // Get all entries into a set
41
+ Set <Map .Entry <String ,Integer >>entrySet =map .entrySet ();
42
+
43
+ // Get key and value from each entry
44
+ for (Map .Entry <String ,Integer >entry :entrySet )
45
+ System .out .println (entry .getValue () +"\t " +entry .getKey ());
46
+ }
47
+
48
+ /** Method Sotres occurrence of words */
49
+ private static void store (Map <String ,Integer >map ,String []words ) {
50
+ for (int i =0 ;i <words .length ;i ++) {
51
+ String key =words [i ].toLowerCase ();
52
+
53
+ if (key .length () >0 &&Character .isLetter (key .charAt (0 ))) {
54
+ if (!map .containsKey (key )) {
55
+ map .put (key ,1 );
56
+ }
57
+ else {
58
+ int value =map .get (key );
59
+ value ++;
60
+ map .put (key ,value );
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }