-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCounter.java
More file actions
587 lines (490 loc) · 22.7 KB
/
WordCounter.java
File metadata and controls
587 lines (490 loc) · 22.7 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class WordCounter extends JFrame {
private JTextArea inputTextArea;
private JTextArea resultTextArea;
private JLabel statsLabel;
private JButton loadFileButton, analyzeButton, clearButton, exportButton;
private JComboBox<String> analysisTypeCombo;
private JCheckBox caseSensitiveCheckBox;
private JProgressBar progressBar;
// Common words set for faster lookup
private static final Set<String> COMMON_WORDS = new HashSet<>(Arrays.asList(
"a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for",
"of", "with", "by", "as", "is", "was", "are", "were", "be", "been",
"have", "has", "had", "do", "does", "did", "will", "would", "could",
"should", "may", "might", "can", "that", "this", "these", "those",
"from", "it", "its", "it's", "i", "you", "he", "she", "we", "they"
));
public WordCounter() {
initializeGUI();
}
private void initializeGUI() {
setTitle("Advanced Word Counter & Analyzer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900, 700);
setLocationRelativeTo(null);
setLayout(new BorderLayout(10, 10));
// Create main panel with padding
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
mainPanel.setBackground(new Color(245, 245, 245));
// Create header
JPanel headerPanel = createHeaderPanel();
mainPanel.add(headerPanel, BorderLayout.NORTH);
// Create input panel
JPanel inputPanel = createInputPanel();
mainPanel.add(inputPanel, BorderLayout.CENTER);
// Create control panel
JPanel controlPanel = createControlPanel();
mainPanel.add(controlPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel(new BorderLayout());
headerPanel.setBackground(new Color(70, 130, 180));
headerPanel.setBorder(new EmptyBorder(10, 15, 10, 15));
JLabel titleLabel = new JLabel("Word Counter & Text Analyzer", JLabel.CENTER);
titleLabel.setFont(new Font("Segoe UI", Font.BOLD, 24));
titleLabel.setForeground(Color.WHITE);
JLabel subtitleLabel = new JLabel("Analyze text and file contents with advanced features", JLabel.CENTER);
subtitleLabel.setFont(new Font("Segoe UI", Font.PLAIN, 14));
subtitleLabel.setForeground(new Color(200, 220, 240));
headerPanel.add(titleLabel, BorderLayout.CENTER);
headerPanel.add(subtitleLabel, BorderLayout.SOUTH);
return headerPanel;
}
private JPanel createInputPanel() {
JPanel inputPanel = new JPanel(new GridLayout(1, 2, 15, 0));
inputPanel.setBackground(new Color(245, 245, 245));
// Left panel - Input
JPanel leftPanel = new JPanel(new BorderLayout(5, 5));
leftPanel.setBorder(createTitledBorder("Input Text"));
leftPanel.setBackground(Color.WHITE);
inputTextArea = new JTextArea();
inputTextArea.setFont(new Font("Consolas", Font.PLAIN, 14));
inputTextArea.setLineWrap(true);
inputTextArea.setWrapStyleWord(true);
JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
inputScrollPane.setPreferredSize(new Dimension(400, 300));
// Add sample text button
JButton sampleTextButton = new JButton("Load Sample Text");
sampleTextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSampleText();
}
});
JPanel inputButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
inputButtonPanel.setBackground(Color.WHITE);
inputButtonPanel.add(sampleTextButton);
leftPanel.add(new JLabel("Enter text or load from file:"), BorderLayout.NORTH);
leftPanel.add(inputScrollPane, BorderLayout.CENTER);
leftPanel.add(inputButtonPanel, BorderLayout.SOUTH);
// Right panel - Results
JPanel rightPanel = new JPanel(new BorderLayout(5, 5));
rightPanel.setBorder(createTitledBorder("Analysis Results"));
rightPanel.setBackground(Color.WHITE);
resultTextArea = new JTextArea();
resultTextArea.setFont(new Font("Consolas", Font.PLAIN, 13));
resultTextArea.setEditable(false);
resultTextArea.setBackground(new Color(250, 250, 250));
JScrollPane resultScrollPane = new JScrollPane(resultTextArea);
resultScrollPane.setPreferredSize(new Dimension(400, 300));
statsLabel = new JLabel("No analysis performed yet");
statsLabel.setFont(new Font("Segoe UI", Font.BOLD, 12));
statsLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
rightPanel.add(new JLabel("Analysis Results:"), BorderLayout.NORTH);
rightPanel.add(resultScrollPane, BorderLayout.CENTER);
rightPanel.add(statsLabel, BorderLayout.SOUTH);
inputPanel.add(leftPanel);
inputPanel.add(rightPanel);
return inputPanel;
}
private JPanel createControlPanel() {
JPanel controlPanel = new JPanel(new BorderLayout(10, 10));
controlPanel.setBackground(new Color(245, 245, 245));
controlPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
// Options panel
JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));
optionsPanel.setBackground(Color.WHITE);
optionsPanel.setBorder(createTitledBorder("Analysis Options"));
analysisTypeCombo = new JComboBox<>(new String[]{
"Total Word Count",
"Word Frequency (All Words)",
"Word Frequency (Exclude Common Words)",
"Top 20 Most Frequent Words",
"Character Count Analysis"
});
analysisTypeCombo.setFont(new Font("Segoe UI", Font.PLAIN, 12));
caseSensitiveCheckBox = new JCheckBox("Case Sensitive");
caseSensitiveCheckBox.setFont(new Font("Segoe UI", Font.PLAIN, 12));
optionsPanel.add(new JLabel("Analysis Type:"));
optionsPanel.add(analysisTypeCombo);
optionsPanel.add(caseSensitiveCheckBox);
// Buttons panel
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
buttonPanel.setBackground(Color.WHITE);
loadFileButton = createStyledButton("Load File", new Color(70, 130, 180));
analyzeButton = createStyledButton("Analyze Text", new Color(60, 179, 113));
clearButton = createStyledButton("Clear All", new Color(220, 20, 60));
exportButton = createStyledButton("Export Results", new Color(255, 140, 0));
// Progress bar
progressBar = new JProgressBar();
progressBar.setVisible(false);
progressBar.setStringPainted(true);
buttonPanel.add(loadFileButton);
buttonPanel.add(analyzeButton);
buttonPanel.add(clearButton);
buttonPanel.add(exportButton);
controlPanel.add(optionsPanel, BorderLayout.NORTH);
controlPanel.add(buttonPanel, BorderLayout.CENTER);
controlPanel.add(progressBar, BorderLayout.SOUTH);
// Add action listeners
addEventListeners();
return controlPanel;
}
private JButton createStyledButton(String text, Color color) {
JButton button = new JButton(text);
button.setFont(new Font("Segoe UI", Font.BOLD, 12));
button.setBackground(color);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
button.setPreferredSize(new Dimension(120, 35));
return button;
}
private TitledBorder createTitledBorder(String title) {
TitledBorder border = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
title
);
border.setTitleFont(new Font("Segoe UI", Font.BOLD, 14));
border.setTitleColor(new Color(70, 70, 70));
return border;
}
private void addEventListeners() {
loadFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadFile();
}
});
analyzeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
analyzeText();
}
});
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearAll();
}
});
exportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportResults();
}
});
}
private void loadFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Select Text File");
// Create file filter
fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
@Override
public boolean accept(File f) {
if (f.isDirectory()) return true;
String name = f.getName().toLowerCase();
return name.endsWith(".txt") || name.endsWith(".java");
}
@Override
public String getDescription() {
return "Text Files (*.txt, *.java)";
}
});
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
String content = readFile(file.getAbsolutePath());
inputTextArea.setText(content);
JOptionPane.showMessageDialog(this, "File loaded successfully: " + file.getName(),
"Success", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void analyzeText() {
String text = inputTextArea.getText().trim();
if (text.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter some text or load a file first.",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
// Show progress
progressBar.setVisible(true);
progressBar.setValue(0);
// Use a simple thread for analysis to avoid GUI freezing
new Thread(new Runnable() {
public void run() {
try {
// Simulate progress
for (int i = 0; i <= 100; i += 10) {
final int progress = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setValue(progress);
}
});
Thread.sleep(100);
}
// Perform analysis
final String result = performAnalysis(text);
// Update GUI on EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resultTextArea.setText(result);
progressBar.setVisible(false);
}
});
} catch (Exception ex) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(WordCounter.this,
"Analysis error: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
progressBar.setVisible(false);
}
});
}
}
}).start();
}
private String performAnalysis(String text) {
int analysisType = analysisTypeCombo.getSelectedIndex();
boolean caseSensitive = caseSensitiveCheckBox.isSelected();
StringBuilder result = new StringBuilder();
long startTime = System.currentTimeMillis();
try {
switch (analysisType) {
case 0: // Total Word Count
int wordCount = countWords(text, caseSensitive);
result.append("=== TOTAL WORD COUNT ANALYSIS ===\n\n");
result.append("Total Words: ").append(wordCount).append("\n");
result.append("Total Characters: ").append(text.length()).append("\n");
result.append("Characters (no spaces): ").append(text.replaceAll("\\s", "").length()).append("\n");
break;
case 1: // Word Frequency (All Words)
Map<String, Integer> freqAll = getWordFrequency(text, caseSensitive, false);
result.append("=== WORD FREQUENCY ANALYSIS (ALL WORDS) ===\n\n");
appendFrequencyResults(result, freqAll);
break;
case 2: // Word Frequency (Exclude Common Words)
Map<String, Integer> freqFiltered = getWordFrequency(text, caseSensitive, true);
result.append("=== WORD FREQUENCY ANALYSIS (FILTERED) ===\n\n");
result.append("Common words excluded: ").append(COMMON_WORDS.size()).append(" words\n\n");
appendFrequencyResults(result, freqFiltered);
break;
case 3: // Top 20 Most Frequent Words
Map<String, Integer> freqTop = getWordFrequency(text, caseSensitive, false);
result.append("=== TOP 20 MOST FREQUENT WORDS ===\n\n");
appendTopWordsResults(result, freqTop);
break;
case 4: // Character Count Analysis
result.append("=== CHARACTER COUNT ANALYSIS ===\n\n");
appendCharacterAnalysis(result, text, caseSensitive);
break;
default:
result.append("Invalid analysis type selected.");
}
long endTime = System.currentTimeMillis();
result.append("\n--- Analysis completed in ").append(endTime - startTime).append(" ms ---");
// Update stats
updateStats(analysisType, text);
} catch (Exception e) {
result.append("Error during analysis: ").append(e.getMessage());
}
return result.toString();
}
private void appendFrequencyResults(StringBuilder result, Map<String, Integer> frequency) {
if (frequency.isEmpty()) {
result.append("No words found for analysis.\n");
return;
}
result.append("Total Unique Words: ").append(frequency.size()).append("\n\n");
// Convert to list and sort manually
List<Map.Entry<String, Integer>> entries = new ArrayList<>(frequency.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e2.getValue().compareTo(e1.getValue()); // Descending order
}
});
for (Map.Entry<String, Integer> entry : entries) {
result.append(String.format("%-20s : %d%n", entry.getKey(), entry.getValue()));
}
}
private void appendTopWordsResults(StringBuilder result, Map<String, Integer> frequency) {
if (frequency.isEmpty()) {
result.append("No words found for analysis.\n");
return;
}
// Convert to list and sort manually
List<Map.Entry<String, Integer>> entries = new ArrayList<>(frequency.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e2.getValue().compareTo(e1.getValue()); // Descending order
}
});
int count = 0;
for (Map.Entry<String, Integer> entry : entries) {
if (count >= 20) break;
result.append(String.format("%-20s : %d%n", entry.getKey(), entry.getValue()));
count++;
}
}
private void appendCharacterAnalysis(StringBuilder result, String text, boolean caseSensitive) {
Map<Character, Integer> charCount = new HashMap<>();
String processedText = caseSensitive ? text : text.toLowerCase();
for (char c : processedText.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
Integer count = charCount.get(c);
if (count == null) {
charCount.put(c, 1);
} else {
charCount.put(c, count + 1);
}
}
}
result.append("Total Characters: ").append(text.length()).append("\n");
int letterDigitCount = 0;
for (int count : charCount.values()) {
letterDigitCount += count;
}
result.append("Letters/Digits Only: ").append(letterDigitCount).append("\n\n");
result.append("Character Frequency:\n");
// Convert to list and sort manually
List<Map.Entry<Character, Integer>> entries = new ArrayList<>(charCount.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> e1, Map.Entry<Character, Integer> e2) {
return e2.getValue().compareTo(e1.getValue()); // Descending order
}
});
int charCountLimit = 0;
for (Map.Entry<Character, Integer> entry : entries) {
if (charCountLimit >= 30) break;
result.append(String.format("'%c' : %d%n", entry.getKey(), entry.getValue()));
charCountLimit++;
}
}
private void updateStats(int analysisType, String text) {
String[] analysisNames = {
"Total Word Count", "Word Frequency", "Filtered Frequency",
"Top 20 Words", "Character Analysis"
};
final String stats = String.format(
"Analysis: %s | Words: %d | Characters: %d",
analysisNames[analysisType],
countWords(text, caseSensitiveCheckBox.isSelected()),
text.length()
);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statsLabel.setText(stats);
}
});
}
private int countWords(String text, boolean caseSensitive) {
String processedText = caseSensitive ? text : text.toLowerCase();
String[] words = processedText.split("[\\s.,!?;:()\\[\\]{}'\"]+");
int count = 0;
for (String word : words) {
if (!word.trim().isEmpty()) {
count++;
}
}
return count;
}
private Map<String, Integer> getWordFrequency(String text, boolean caseSensitive, boolean excludeCommon) {
String processedText = caseSensitive ? text : text.toLowerCase();
String[] words = processedText.split("[\\s.,!?;:()\\[\\]{}'\"]+");
Map<String, Integer> frequency = new LinkedHashMap<>();
for (String word : words) {
if (word.trim().isEmpty()) continue;
if (excludeCommon && COMMON_WORDS.contains(word.toLowerCase())) continue;
Integer count = frequency.get(word);
if (count == null) {
frequency.put(word, 1);
} else {
frequency.put(word, count + 1);
}
}
return frequency;
}
private void clearAll() {
inputTextArea.setText("");
resultTextArea.setText("");
statsLabel.setText("No analysis performed yet");
progressBar.setVisible(false);
}
private void exportResults() {
if (resultTextArea.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "No results to export. Please analyze some text first.",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Export Results");
fileChooser.setSelectedFile(new File("word_analysis_results.txt"));
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (PrintWriter writer = new PrintWriter(file)) {
writer.write(resultTextArea.getText());
JOptionPane.showMessageDialog(this, "Results exported successfully to: " + file.getAbsolutePath(),
"Export Successful", JOptionPane.INFORMATION_MESSAGE);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Error exporting results: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void loadSampleText() {
String sampleText = "This is a sample text for demonstration purposes. " +
"You can analyze this text to see how the word counter works. " +
"The quick brown fox jumps over the lazy dog. " +
"Word frequency analysis helps understand text patterns and content structure.";
inputTextArea.setText(sampleText);
}
private String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
} finally {
if (reader != null) {
reader.close();
}
}
return content.toString();
}
public static void main(String[] args) {
// Simple main method without look and feel changes
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new WordCounter().setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}