-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCJT_Project2.java
More file actions
94 lines (69 loc) · 2.84 KB
/
Copy pathCJT_Project2.java
File metadata and controls
94 lines (69 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.io.*;
import java.util.*;
public class CJT_Project2 {
public static List<String> preprocessText(String text, Set<String> stopwords) {
List<String> words = new ArrayList<>();
String[] tokens = text.toLowerCase().split("\\W+");
for (String word : tokens) {
if (!stopwords.contains(word) && !word.isEmpty()) {
words.add(word);
}
}
return words;
}
public static Map<String, Integer> countFrequencies(List<String> words) {
Map<String, Integer> freqMap = new HashMap<>();
for (String word : words) {
freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
}
return freqMap;
}
public static List<Map.Entry<String, Integer>> getTopWords(Map<String, Integer> freqMap, int N) {
List<Map.Entry<String, Integer>> list = new ArrayList<>(freqMap.entrySet());
list.sort((a, b) -> b.getValue() - a.getValue());
return list.subList(0, Math.min(N, list.size()));
}
public static double calculateRatio(List<Map.Entry<String, Integer>> topWords, int totalWords) {
int sum = 0;
for (Map.Entry<String, Integer> entry : topWords) {
sum += entry.getValue();
}
return (double) sum / totalWords;
}
public static int countPunctuation(String text) {
int count = 0;
for (char ch : text.toCharArray()) {
if (!Character.isLetterOrDigit(ch) && !Character.isWhitespace(ch)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
StringBuilder textBuilder = new StringBuilder();
Scanner textScanner = new Scanner(new File("alice29.txt"));
while (textScanner.hasNextLine()) {
textBuilder.append(textScanner.nextLine()).append(" ");
}
textScanner.close();
String text = textBuilder.toString();
Set<String> stopwords = new HashSet<>();
Scanner stopScanner = new Scanner(new File("stopwords.txt"));
while (stopScanner.hasNext()) {
stopwords.add(stopScanner.next().toLowerCase());
}
stopScanner.close();
List<String> processed = preprocessText(text, stopwords);
Map<String, Integer> freq = countFrequencies(processed);
List<Map.Entry<String, Integer>> top = getTopWords(freq, 10);
double ratio = calculateRatio(top, processed.size());
System.out.println("Total words AFTER preprocessing: " + processed.size());
System.out.println("Top 10 Words: " + top);
System.out.println("Ratio: " + ratio);
System.out.println("Punctuation Count: " + countPunctuation(text));
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}