-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpellCheck.java
819 lines (697 loc) · 29.1 KB
/
SpellCheck.java
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// Jeffrey Ramos, Summer 2020
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
class TrieNode
{
int count;
TrieNode [] children;
TrieNode subtrie;
public TrieNode()
{
this.count = 0;
children = new TrieNode[26];
}
}
public class SpellCheck implements ActionListener
{
private TrieNode dictionaryRoot;
private TrieNode predictRoot;
private JTextArea text;
private JScrollPane scroll;
private JButton sugg1;
private JFrame frame;
private JLabel misspell;
private String str;
private Dimension area;
private void initComponentsDictionary() throws IOException
{
dictionaryRoot = buildTrie("dictionary.txt");
frame = new JFrame("SpellCheck");
frame.setSize(new Dimension(1600, 1600));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sugg1 = new JButton();
sugg1.setPreferredSize(new Dimension(125, 55));
sugg1.addActionListener(this);
misspell = new JLabel();
area = new Dimension(0,0);
text = new JTextArea();
text.setPreferredSize(new Dimension(1000, 1000));
text.setFont(new Font("TimesRoman", Font.PLAIN, 25));
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.addKeyListener(new KeyListener()
{
@Override
public void keyTyped(KeyEvent e)
{}
@Override
public void keyPressed(KeyEvent e)
{
final int enter = 10;
final int space = 32;
if (e.getKeyCode() == space)
{
str = text.getText();
StringBuilder builder = new StringBuilder(str);
String prevStr = "";
Highlighter highlighter;
HighlightPainter painter;
if (str.lastIndexOf(" ") >= 0)
{
prevStr = str;
str = str.substring(str.lastIndexOf(" ") + 1, str.length());
System.out.println("str is " + str);
if (getTerminalNode(predictRoot, str) != null)
{
sugg1.setText(getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str));
}
else
{
sugg1.setText("");
}
}
else
{
if (containsWord(predictRoot, str) && getTerminalNode(predictRoot, str).subtrie != null)
{
sugg1.setText(getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str));
}
else
{
sugg1.setText("");
}
}
prevStr = "";
boolean flag = true;
str = text.getText();
if (str.replaceAll(" ", "").equals(""))
{
return;
}
if (str.lastIndexOf(" ") < 0)
{
System.out.println("We're working with " + str);
builder = new StringBuilder(str);
}
else
{
str = str.substring(str.lastIndexOf(" ")+1, str.length());
System.out.println("We got " + str);
builder = new StringBuilder(str);
}
if (isNumeric(builder.toString()))
{
return;
}
else if (builder.toString().indexOf(' ') < 0)
{
if (!containsWord(dictionaryRoot, builder.toString()))
{
if (!Character.isAlphabetic(builder.charAt(builder.length() - 1)))
{
builder.delete(builder.length() - 1, builder.length());
}
str = text.getText();
highlighter = text.getHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
int p0 = str.indexOf(builder.toString());
int p1 = p0 + builder.length();
try
{
highlighter.addHighlight(p0, p1, painter);
}
catch (BadLocationException ex)
{
Logger.getLogger(SpellCheck.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(builder.toString() + " is not a word.");
flag = false;
}
}
else if (isNumeric(builder.substring(0, builder.indexOf(" "))))
{
builder.delete(0, builder.indexOf(" ") + 1);
}
else if (!containsWord(dictionaryRoot, builder.substring(0, builder.indexOf(" "))))
{
str = text.getText();
int p0 = builder.indexOf(builder.toString());
int p1 = p0 + builder.lastIndexOf(" ");
try
{
highlighter = text.getHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
highlighter.addHighlight(p0, p1, painter);
removeHighlights(text);
}
catch (BadLocationException ex)
{
Logger.getLogger(SpellCheck.class.getName()).log(Level.SEVERE, null, ex);
}
flag = false;
}
else
{
str = builder.substring(builder.toString().lastIndexOf(' ')+1, builder.length());
predictRoot = insert(predictRoot, str);
if (!prevStr.equals("") && prevStr.charAt(prevStr.length() - 1) != '.')
{
System.out.println("Adding " + str + " to " + prevStr);
TrieNode prevStrRoot = getTerminalNode(predictRoot, prevStr).subtrie;
getTerminalNode(predictRoot, prevStr).subtrie = insert(prevStrRoot, str);
prevStr = str;
}
else if (prevStr.equals(""))
{
prevStr = str;
}
else
{
prevStr = "";
}
}
builder.delete(0, builder.indexOf(" ") + 1);
if (flag)
{
insert(predictRoot, builder.toString());
System.out.println("No spelling errors detected.");
}
}
else if (e.getKeyCode() == enter)
{
str = text.getText();
StringBuilder builder = new StringBuilder(str);
String prevStr = "";
boolean flag = true;
System.out.println("num cols: " + text.getColumns());
System.out.println("caret pos: " + text.getCaretPosition());
while (builder.length() > 0)
{
if (isNumeric(builder.toString()))
{
break;
}
if (builder.toString().indexOf(' ') < 0)
{
if (!containsWord(dictionaryRoot, builder.toString()))
{
if (!Character.isAlphabetic(builder.charAt(builder.length() - 1)))
{
builder.delete(builder.length() - 1, builder.length());
}
System.out.println(builder.toString() + " is not a word.");
flag = false;
}
else
{
if (prevStr.equals(""))
{
predictRoot = insert(predictRoot, builder.toString());
System.out.println(getTerminalNode(predictRoot, builder.toString()).count);
break;
}
else
{
builder.append(" ");
str = builder.substring(0, builder.indexOf(" "));
System.out.println("prevStr = " + prevStr);
TrieNode prevStrRoot = getTerminalNode(predictRoot, prevStr).subtrie;
getTerminalNode(predictRoot, prevStr).subtrie = insert(prevStrRoot, str);
prevStr = str;
}
}
break;
}
else if (isNumeric(builder.substring(0, builder.indexOf(" "))))
{
builder.delete(0, builder.indexOf(" ") + 1);
continue;
}
else if (!containsWord(dictionaryRoot, builder.substring(0, builder.indexOf(" "))))
{
System.out.println(builder.substring(0, builder.indexOf(" ")) + " is not a word.");
flag = false;
}
else
{
str = builder.substring(0, builder.indexOf(" "));
System.out.println("Inserting " + str);
predictRoot = insert(predictRoot, str);
if (!prevStr.equals("") && prevStr.charAt(prevStr.length() - 1) != '.')
{
System.out.println("Adding " + str + " to " + prevStr);
TrieNode prevStrRoot = getTerminalNode(predictRoot, prevStr).subtrie;
getTerminalNode(predictRoot, prevStr).subtrie = insert(prevStrRoot, str);
prevStr = str;
}
else if (prevStr.equals(""))
{
prevStr = str;
}
else
{
prevStr = "";
}
}
builder.delete(0, builder.indexOf(" ") + 1);
}
if (flag)
{
insert(predictRoot, builder.toString());
System.out.println("No spelling errors detected.");
}
}
}
@Override
public void keyReleased(KeyEvent e)
{}
});
scroll = new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBounds(300, 25, 1000, 1000);
frame.add(sugg1);
frame.add(scroll);
frame.add(misspell);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if (sugg1.getText().equals(""))
{
return;
}
text.setText(text.getText() + getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str) + " ");
if (str.lastIndexOf(" ") >= 0)
{
str = str.substring(str.lastIndexOf(" ") + 1, str.length());
}
System.out.println("str is " + str);
System.out.println(getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str));
str = getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str);
sugg1.setText(getMostFrequentWord(getTerminalNode(predictRoot, str).subtrie, str));
}
// Code found on: https://www.baeldung.com/java-check-string-number
public static boolean isNumeric(String strNum)
{
if (strNum == null)
{
return false;
}
try
{
double d = Double.parseDouble(strNum);
}
catch (NumberFormatException nfe)
{
return false;
}
return true;
}
public static int semiLastIndexOf(String str, char semiLast)
{
int count = 0;
for (int i = str.length() - 1; i >= 0; i--)
{
if (str.charAt(i) == semiLast)
{
if (count < 2)
{
count++;
}
if (count == 2)
{
return i;
}
}
}
return -1;
}
public void removeHighlights(JTextComponent textComp)
{
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i = 0; i < hilites.length; i++)
{
if (hilites[i].getPainter() instanceof HighlightPainter)
{
hilite.removeHighlight(hilites[i]);
}
}
}
// Insert a string into a trie. This function returns the root of the trie.
public TrieNode insert(TrieNode root, String str)
{
TrieNode temp;
str = str.toLowerCase();
if (root == null)
{
root = new TrieNode();
}
if (str.equals(""))
{
return root;
}
temp = root;
for (int i = 0; i < str.length(); i++)
{
if (!Character.isAlphabetic(str.charAt(i)) && str.charAt(i) == '-')
{
continue;
}
else if (!Character.isAlphabetic(str.charAt(i)) && str.charAt(i) != '-')
{
return root;
}
int index = (int) str.charAt(i) - 'a';
// Before the wizard can move forward to the next node, (s)he needs to
// make sure that node actually exists. If not, create it!
if (temp.children[index] == null)
{
temp.children[index] = new TrieNode();
}
// Now the wizard is able to jump forward.
temp = temp.children[index];
}
// When we break out of the for-loop, the wizard should be at the terminal
// node that represents the string we're trying to insert.
temp.count++;
return root;
}
public void createSubtrie(TrieNode root, String word)
{
insert(root.subtrie, word);
}
// Helper function called by printTrie().
// public void printTrieHelper(TrieNode root, StringBuilder buffer, int k)
// {
// if (root == null)
// {
// return;
// }
//
// if (root.count > 0)
// {
// System.out.println(buffer.toString() + " (" + root.count + ")");
// }
//
// for (int i = 0; i < 26; i++)
// {
// buffer.append((char) ('a' + i));
// printTrieHelper(root.children[i], buffer, k + 1);
// buffer.delete(k, buffer.length());
// }
// }
// If printing a subtrie, the second parameter should be true; otherwise, if
// printing the main trie, the second parameter should be false.
// public void printTrie(TrieNode root, boolean useSubtrieFormatting)
// {
// StringBuilder buffer = new StringBuilder();
//
// if (useSubtrieFormatting)
// {
// buffer.append("- ");
// printTrieHelper(root, buffer, 2);
// }
// else
// {
// printTrieHelper(root, buffer, 0);
// }
// }
// Returns the terminal node of a string within a trie.
public TrieNode getTerminalNode(TrieNode root, String str)
{
int index;
str = str.toLowerCase();
TrieNode temp = root;
if (root == null)
{
return null;
}
// Finds the terminal node of "str" in the trie by looping through the length of the string.
for (int i = 0; i < str.length(); i++)
{
// If the string contains a non-alphabetical character, we don't include it in our traversal
// through the trie.
if (!Character.isAlphabetic(str.charAt(i)))
{
continue;
}
index = (int) (str.charAt(i) - 'a');
// If the index of the corresponding child is non-NULL, then we set the our traversal variable
// "temp" equal to that child.
if (temp.children[index] != null)
{
temp = temp.children[index];
}
}
return temp;
}
// Creates a trie and inserts all words within a file into it.
public TrieNode buildTrie(String filename) throws IOException
{
TrieNode root = null;
TrieNode terminal = null;
String str = "";
Scanner fileReader = new Scanner(new File(filename));
int length = 0;
while (fileReader.hasNext())
{
str = fileReader.next();
// Insert the current word into the trie.
root = insert(root, str);
// Determines whether or not the current string is the first word of the string.
// If it is, then there is no subtrie for this first word to go in.
if (terminal != null)
{
// Inserts the current word into the subtrie of the previous word.
terminal.subtrie = insert(terminal.subtrie, str);
// If the last character of the current string is a punctuator that signals the end of a
// sentence, we reset the "terminal" variable back to NULL and go onto the next word.
if (str.charAt(str.length() - 1) == '.' || str.charAt(str.length() - 1) == '!'
|| str.charAt(str.length() - 1) == '?')
{
terminal = null;
continue;
}
}
// Set the "terminal" TrieNode pointer equal to the terminal node of the string.
terminal = getTerminalNode(root, str);
}
fileReader.close();
return root;
}
// // Prints a word from a trie followed by the word that most frequently follows it in the
// // corpus used. Does this process "n" times.
// public void nextWord(TrieNode root, String str, int n)
// {
// if (root == null)
// {
// return;
// }
//
// // Prints the current string. Also, prints a space after it if it's not the last word being
// // printed, or an empty string if it is.
// System.out.format("%s%s", str, (n > 0 && getTerminalNode(root, str).subtrie != null) ? " " : "");
//
// // If the number of times we need to print has not been reached and if the current string does
// // have a subtrie, then we find the word that most frequently follows the current string.
// // (We search for the string that was most frequently inserted into the current string's subtrie)
// if (n > 0 && getTerminalNode(root, str).subtrie != null)
// {
// // Finds the most frequent word in the current string's subtrie.
// str = getMostFrequentWord(getTerminalNode(root, str).subtrie, str);
// atHelper(root, str, n - 1);
// }
//
// }
// Returns the bigger of two numbers passed in as parameters.
public int max(int a, int b)
{
return (a > b) ? a : b;
}
// Searches the trie for the node with the biggest count and returns that maximum value.
public int findMaxCount(TrieNode root, int maxVal)
{
TrieNode temp = root;
if (root == null)
{
return maxVal;
}
// If the count of the current node is greater than or equal to 1, then we find the maximum value
// between "maxVal" and the "count" member. If so, we replace the value stored at "maxVal" with
// the new greater value, that being the value that the "count" member of the node we are at.
if (temp.count >= 1)
{
maxVal = max(maxVal, root.count);
}
// We loop through each child of the current node to search for the biggest value.
for (int i = 0; i < 26; i++)
{
maxVal = findMaxCount(temp.children[i], maxVal);
}
return maxVal;
}
// Searches for the most common word in the trie in alphabetical order and copies that word into the
// string "str" passed into the parameters.
public String searchMostCommon(TrieNode root, StringBuilder buffer, int maxVal, Integer found)
{
TrieNode temp = root;
if (root == null)
{
return "";
}
// Checks if we found the node with the maximum "count" value and if we haven't already found a
// node with the same maximum "count" value. If so, we copy what was in "buffer" into "str" and
// sets *found to 1 to indicate that we found the word that occurs most frequently.
if (temp.count == maxVal && found != 1)
{
found = 1;
return buffer.toString();
}
for (int i = 0; i < 26; i++)
{
// If the child we are looking at is non-null, then we go there and insert the corresponding
// letter into str. We then look at all of its children and continue to search for letters to
// insert into "buffer".
temp = temp.children[i];
buffer.append((char) ('a' + i));
String str = searchMostCommon(temp, buffer, maxVal, found);
// Makes a recursive call with an index that is 1 greater than it was before in order to insert
// into the next index in "buffer".
if (!str.equals(""))
{
return str;
}
// Reset our traversal TrieNode pointer variable back to the root, or the terminal node of the
// prefix.
buffer.delete(buffer.length() - 1, buffer.length());
temp = root;
}
// We then reset "buffer" to what it was before searching, which handles the
// case where we didn't find the word and we want to "erase" what we inserted.
return "";
}
// Copies the the word that was most frequently inserted into the trie into the string "str" passed
// into the parameters.
public String getMostFrequentWord(TrieNode root, String str)
{
StringBuilder buffer = new StringBuilder();
if (root == null)
{
return "";
}
// Parameters are as follows: TrieNode *root, char *str, char *buffer, int maxVal, int index,
// int *found. "maxVal" (the second parameter in the findMaxCount function call) is 0 because the
// maximum value should be 0 until a bigger vale is found. "index" is also 0 because we are
// inserting into "buffer" starting from the first index in "buffer". The string "buffer"
// contains will be copied into str within the function call.
return searchMostCommon(root, buffer, findMaxCount(root, 0), 0);
}
// Returns true if "str" was found in the trie. Returns false otherwise.
public boolean containsWord(TrieNode root, String str)
{
int index;
TrieNode temp = root;
str = str.toLowerCase();
// Loops through the trie in order to attempt to find "str" in the trie.
for (int i = 0; i < str.length(); i++)
{
// If we reach a NULL node, the word must not be in the trie.
if (temp == null)
{
return false;
}
if (!Character.isAlphabetic(str.charAt(i)))
{
continue;
}
index = (int) (str.charAt(i) - 'a');
temp = temp.children[index];
}
// If we reached the last node in the path we take trying to find "str" in the trie and it
// contains a count greater than 0, that means that the word is in the trie. Return true.
if (temp != null && temp.count >= 1)
{
return true;
}
// Otherwise, we return false.
return false;
}
// A helper function that returns the number of times that a word beginning with a prefix is found
// by searching for all words that come out from the terminal node at the end of the prefix string.
public int searchPrefixHelper(TrieNode root)
{
TrieNode temp = root;
int count = 0;
if (root == null)
{
return 0;
}
// We add the value stored in the "count" member of the TrieNode to the "count" variable.
count += temp.count;
// Loops through all the children to find any words that begin with the prefix.
for (int i = 0; i < 26; i++)
{
// If the letter we are analyzing is in the trie, we go to the node that the letter's path leads
// to. We also add all values stored within each "count" member of each TrieNode.
if (temp.children[i] != null)
{
temp = temp.children[i];
count += searchPrefixHelper(temp);
}
// Reset our traversal TrieNode pointer variable back to the root, or the terminal node of the
// prefix.
temp = root;
}
return count;
}
// Returns the number of times that a word beginning with a prefix is found.
public boolean prefixCount(TrieNode root, String str)
{
TrieNode temp = root;
int index;
str = str.toLowerCase();
// If the root is NULL, there cannot be any wrds that begin with the prefix in the trie so we
// return false.
if (root == null)
{
return false;
}
// Moves the temp pointer to the terminal node of the prefix.
for (int i = 0; i < str.length(); i++)
{
if (temp == null)
{
return false;
}
if (!Character.isAlphabetic(str.charAt(i)))
{
continue;
}
index = (int) (str.charAt(i) - 'a');
temp = temp.children[index];
}
if (searchPrefixHelper(temp) > 0)
{
return true;
}
return false;
}
// Creates a new instance of the SpellCheck class.
// Starts up the GUI and inserts an English language dictionary into a trie.
public static void main(String[] args) throws IOException
{
SpellCheck sp = new SpellCheck();
sp.initComponentsDictionary();
}
}