-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTweakedPeterNorvigSpellChecker.cs
731 lines (638 loc) · 26 KB
/
TweakedPeterNorvigSpellChecker.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SpellChecker_GUI
{
///////////////////////////
//
// Tweaks to the original:
//
// -Added the capability to spell check Portuguese, side by side with English.
// -Added the capability of words with ‘ to the English language.
// -Added in the Portuguese version the change of ‘ç’ to ‘ss’ and ‘ss’ to ‘ç’.
// -Added support for returning a list of words suggestions with a complex sorting order
// -Added support for loading words lists directly in a more compact way (faster).
// -Added performance optimizations
//
internal class TweakedPeterNorvigSpellChecker
{
private const int FreqNumberOfCorrectWordsWithOutFreq = 10;
// English
private Dictionary<string, int> EN_wordDic;
private static readonly string EN_alphabet = @"abcdefghijklmnopqrstuvwxyz'";
private static readonly char[] EN_alphabetArray = EN_alphabet.ToArray();
// Portuguese
private Dictionary<string, int> PT_wordDic;
private static readonly string PT_alphabet = @"abcdefghijklmnopqrstuvwxyzãõàáéíóúâêôç-";
private static readonly char[] PT_alphabetArray = PT_alphabet.ToArray();
// Currently using
private Dictionary<string, int> NWORDS;
private string alphabet;
private char[] alphabetArray;
private Regex regExCompWords;
private Utils.Language currentLang;
internal Utils.Language CurrentLang
{
get
{
return currentLang;
}
set
{
currentLang = value;
switch (value)
{
case Utils.Language.English:
NWORDS = EN_wordDic;
alphabet = EN_alphabet;
alphabetArray = EN_alphabetArray;
regExCompWords = Utils.RegExCompWordEN;
break;
case Utils.Language.Portuguese:
NWORDS = PT_wordDic;
alphabet = PT_alphabet;
alphabetArray = PT_alphabetArray;
regExCompWords = Utils.RegExCompWordPT;
break;
}
}
}
internal TweakedPeterNorvigSpellChecker(Utils.Language lang)
{
EN_wordDic = new Dictionary<string, int>(100000);
PT_wordDic = new Dictionary<string, int>(100000);
currentLang = lang;
}
internal void trainFromTextFile(Utils.Language lang, string trainPath)
{
string trainText = File.ReadAllText(trainPath, Encoding.UTF8);
Regex regExWordsLang = null;
Dictionary<string, int> dicWords = null;
switch (lang)
{
case Utils.Language.English:
regExWordsLang = Utils.RegExCompWordEN;
dicWords = EN_wordDic;
break;
case Utils.Language.Portuguese:
regExWordsLang = Utils.RegExCompWordPT;
dicWords = PT_wordDic;
break;
}
int numParts = 10;
int partNumCharacters = trainText.Length / 10;
for (int i = 0; i < numParts; i++)
{
int beginIndex = partNumCharacters * i;
string trainTextPart = trainText.Substring(beginIndex, partNumCharacters);
MatchCollection mColl = regExWordsLang.Matches(trainTextPart);
foreach (Match match in mColl)
{
string word = match.Value.ToLower();
int counts;
if (dicWords.TryGetValue(word, out counts))
dicWords[word] = ++counts;
else
dicWords.Add(word, 1);
}
}
}
internal void trainFromWordListFile(Utils.Language lang, string trainPath, bool withFreq)
{
string wordListText = File.ReadAllText(trainPath, Encoding.UTF8);
Regex regExWordsLang = null;
Dictionary<string, int> dicWords = null;
switch (lang)
{
case Utils.Language.English:
regExWordsLang = Utils.RegExCompWordEN;
dicWords = EN_wordDic;
break;
case Utils.Language.Portuguese:
regExWordsLang = Utils.RegExCompWordPT;
dicWords = PT_wordDic;
break;
}
string[] lines = wordListText.Split('\n');
foreach (var line in lines)
{
if (line.Trim() == "")
continue;
if (withFreq)
{
string[] items = line.Split(' ');
string word = items[0].Trim().ToLower();
int count = Int32.Parse(items[1]);
if (!dicWords.ContainsKey(word))
{
dicWords.Add(word, count);
}
}
else
{
// WithOutFreq
string word = line.Trim().ToLower();
int count;
if (dicWords.TryGetValue(word, out count))
{
dicWords[word] = count + FreqNumberOfCorrectWordsWithOutFreq;
}
else
{
dicWords.Add(word, FreqNumberOfCorrectWordsWithOutFreq);
}
}
}
}
private HashSet<string> edits1(string word)
{
//List<Tuple<string, string>> splitsList = new List<Tuple<string, string>>();
List<Utils.MyTupleStr> splitsList = new List<Utils.MyTupleStr>();
List<string> deletesList = new List<string>(50);
List<string> transposesList = new List<string>(50);
List<string> replacesList = new List<string>(1000);
List<string> insertsList = new List<string>(1000);
// Splits
for (int i = 0; i < word.Length + 1; i++)
{
//splitsList.Add(new Tuple<string, string>(word.Substring(0, i), word.Substring(i)));
splitsList.Add(new Utils.MyTupleStr(word.Substring(0, i), word.Substring(i)));
}
// Deletes
foreach (var tuple in splitsList)
{
string a = tuple.Item1;
string b = tuple.Item2;
if (b != "")
deletesList.Add(a + b.Substring(1));
}
// Transposes
foreach (var tuple in splitsList)
{
string a = tuple.Item1;
string b = tuple.Item2;
if (b.Length > 1)
transposesList.Add($"{a}{b[1]}{b[0]}{b.Substring(2)}");
}
// Replaces
foreach (var tuple in splitsList)
{
string a = tuple.Item1;
string b = tuple.Item2;
if (b != "")
{
foreach (var c in alphabetArray)
replacesList.Add($"{a}{c}{b.Substring(1)}");
}
}
if (currentLang == Utils.Language.Portuguese)
{
// Replace "ç" => "ss"
for (int i = 0; i < word.Length; i++)
{
if (word[i] == 'ç')
{
string a = word.Substring(0, i);
string b = word.Substring(i + 1);
replacesList.Add($"{a}{"ss"}{b}");
}
}
// Replace "ss" => "ç"
for (int i = 0; i < word.Length; i++)
{
if (( i != 0) && (word.Length > 1))
{
if ((word[i - 1] == 's') && (word[i] == 's'))
{
string a = word.Substring(0, i-1);
string b = word.Substring(i + 1);
replacesList.Add($"{a}{"ç"}{b}");
}
}
}
}
// Inserts
foreach (var tuple in splitsList)
{
string a = tuple.Item1;
string b = tuple.Item2;
foreach (var c in alphabetArray)
insertsList.Add($"{a}{c}{b}");
}
int capacity = deletesList.Count + transposesList.Count + replacesList.Count + insertsList.Count;
deletesList.Capacity = capacity;
deletesList.AddRange(transposesList);
deletesList.AddRange(replacesList);
deletesList.AddRange(insertsList);
HashSet<string> set = new HashSet<string>(deletesList);
return set;
}
private HashSet<String> known_edits2(string word)
{
HashSet<string> set = new HashSet<string>();
foreach (var e1 in edits1(word))
{
foreach (var e2 in edits1(e1))
{
if (NWORDS.ContainsKey(e2))
set.Add(e2);
}
}
return set;
}
private HashSet<String> known(IEnumerable<string> words)
{
HashSet<string> set = new HashSet<string>();
foreach (var w in words)
{
int count;
if (NWORDS.TryGetValue(w, out count))
{
set.Add(w);
}
}
return set;
}
private List<WordFreq> knownList(HashSet<string> wordsAlreadySeen, IEnumerable<string> words)
{
List<WordFreq> resultList = new List<WordFreq>();
foreach (var w in words)
{
if (!wordsAlreadySeen.Contains(w))
{
int count;
if (NWORDS.TryGetValue(w, out count))
{
wordsAlreadySeen.Add(w);
resultList.Add(new WordFreq(w, count));
}
}
}
return resultList;
}
private List<WordFreq> knownList_edits2(HashSet<string> wordsAlreadySeen, string word)
{
List<WordFreq> resultList = new List<WordFreq>(30);
foreach (var e1 in edits1(word))
{
foreach (var e2 in edits1(e1))
{
if (!wordsAlreadySeen.Contains(e2))
{
int count;
if (NWORDS.TryGetValue(e2, out count))
{
wordsAlreadySeen.Add(e2);
resultList.Add(new WordFreq(e2, count));
}
}
}
}
return resultList;
}
// Note: Note used because it's to heavy in terms of CPU.
private List<WordFreq> knownList_edits3(HashSet<string> wordsAlreadySeen, string word)
{
List<WordFreq> resultList = new List<WordFreq>(50);
foreach (var e1 in edits1(word))
{
foreach (var e2 in edits1(e1))
{
foreach (var e3 in edits1(e2))
{
if (!wordsAlreadySeen.Contains(e3))
{
int count;
if (NWORDS.TryGetValue(e3, out count))
{
wordsAlreadySeen.Add(e3);
resultList.Add(new WordFreq(e3, count));
}
}
}
}
}
return resultList;
}
internal bool wordExists(string word)
{
int count;
if (NWORDS.TryGetValue(word.ToLower(), out count))
return true;
else
return false;
}
internal List<WordFreq> correct(string word, out bool wordIsCorrect)
{
List<WordFreq> resultsList = new List<WordFreq>();
if (word.Length == 0)
{
wordIsCorrect = true;
return resultsList;
}
wordIsCorrect = false;
word = word.ToLower();
HashSet<string> set = new HashSet<string>();
set = known(new List<string> { word });
if (set.Count == 0)
{
set = known(edits1(word));
if (set.Count == 0)
{
set = known_edits2(word);
if (set.Count == 0)
set.Add(word);
}
}
else
{
wordIsCorrect = true;
}
foreach (var w in set)
{
int count;
if (NWORDS.TryGetValue(w, out count))
{
resultsList.Add(new WordFreq(w,count));
}
}
resultsList = resultsList.OrderByDescending(o => (o.Word[0] == word[0]) ? 5 : 1).ThenByDescending(o => o.Count).ToList();
return resultsList;
}
// This version implements a more agressive optimisation on the words that are suggested,
// specially in details of the order by witch they are sorted.
// It also generates more possible words, depending on the size of the word, it
// returns words with edit distances of one two. Not three.
internal List<WordFreq> correctV2(string word, out bool wordIsCorrect)
{
List<WordFreq> resultsList = new List<WordFreq>(50);
if (word.Length == 0)
{
wordIsCorrect = true;
return resultsList;
}
wordIsCorrect = false;
word = word.ToLower();
HashSet<string> dicWordsAlreadySeen = new HashSet<string>();
resultsList = knownList(dicWordsAlreadySeen, new List<string> { word });
if (resultsList.Count != 0)
return resultsList;
List<WordFreq> resultsListSecondPart = new List<WordFreq>(50);
List<WordFreq> resultsListEdit_1 = null;
List<WordFreq> resultsListEdit_2 = null;
//List<WordFreq> resultsListEdit_3 = null;
// Edit 1 distance.
resultsListEdit_1 = knownList(dicWordsAlreadySeen, edits1(word));
if (resultsListEdit_1.Count != 0)
{
resultsListEdit_1 = resultsListEdit_1.OrderByDescending(o => (o.Word[0] == word[0]) ? 5 : 1).ThenByDescending(o => o.Count).ToList();
foreach (var wordFreq in resultsListEdit_1)
{
if (wordFreq.Word[0] == word[0])
// Copy word started with letter, to the first part.
resultsList.Add(wordFreq);
else
// Copy rest of the words to the second part.
resultsListSecondPart.Add(wordFreq);
}
}
// Edit 2 distance.
if ( ((word.Length >= 5) || (resultsListEdit_1.Count == 0)) && (word.Length <= 25) )
{
resultsListEdit_2 = knownList_edits2(dicWordsAlreadySeen, word);
if (resultsListEdit_2.Count != 0)
{
resultsListEdit_2 = resultsListEdit_2.OrderByDescending(o => (o.Word[0] == word[0]) ? 5 : 1).ThenByDescending(o => o.Count).ToList();
foreach (var wordFreq in resultsListEdit_2)
{
if (wordFreq.Word[0] == word[0])
// Copy word started with letter, to the first part.
resultsList.Add(wordFreq);
else
// Copy rest of the words to the second part.
resultsListSecondPart.Add(wordFreq);
}
}
}
/*
// Edit 3 distance.
if (word.Length >= 10 || ((resultsListEdit_1.Count == 0) && (resultsListEdit_2.Count == 0)) )
{
resultsListEdit_3 = knownList_edits3(dicWordsAlreadySeen, word);
if (resultsListEdit_3.Count != 0)
{
resultsListEdit_3 = resultsListEdit_3.OrderByDescending(o => (o.Word[0] == word[0]) ? 5 : 1).ThenByDescending(o => o.Count).ToList();
foreach (var wordFreq in resultsListEdit_3)
{
if (wordFreq.Word[0] == word[0])
// Copy word started with letter, to the first part.
resultsList.Add(wordFreq);
else
// Copy rest of the words to the second part.
resultsListSecondPart.Add(wordFreq);
}
}
}
*/
resultsList.AddRange(resultsListSecondPart);
return resultsList;
}
internal bool dataOnWord(string word, out int counts)
{
if (NWORDS.TryGetValue(word.ToLower(), out counts))
return true;
else
return false;
}
internal static string wordListToString(List<WordFreq> wordsList)
{
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < wordsList.Count; i++)
{
WordFreq wL = wordsList[i];
if (i != 0)
strBuilder.Append(",");
strBuilder.Append($" {wL.Word} : {wL.Count}");
}
return strBuilder.ToString();
}
}
internal class Test_TweakedPeterNorvigSpellChecker
{
internal static void runTests()
{
runTestEN(); // From big.txt text file.
//runTestPT(); // From text file.
runTestWordListPT(); // From word dictionary.
}
private static void runTestEN()
{
string trainFilePath = @"..\..\trainFiles\big.txt";
TweakedPeterNorvigSpellChecker sp = new TweakedPeterNorvigSpellChecker(Utils.Language.English);
sp.CurrentLang = Utils.Language.Portuguese;
sp.CurrentLang = Utils.Language.English;
sp.trainFromTextFile(Utils.Language.English, trainFilePath);
testWord(sp, "Helo", "Hello");
int counts = 0;
string word = "Hello";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
word = "felo";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
//>>> correct('speling')
// 'spelling'
//>>> correct('korrecter')
// 'corrector'
testWord(sp, "speling", "spelling");
testWord(sp, "korrecter", "corrector"); // Corrector doesn't exists in the big.txt file.
/*
correct('economtric') => 'economic'(121); expected 'econometric'(1)
correct('embaras') => 'embargo'(8); expected 'embarrass'(1)
correct('colate') => 'coat'(173); expected 'collate'(1)
correct('orentated') => 'orentated'(1); expected 'orientated'(1)
correct('unequivocaly') => 'unequivocal'(2); expected 'unequivocally'(1)
correct('generataed') => 'generate'(2); expected 'generated'(1)
correct('guidlines') => 'guideline'(2); expected 'guidelines'(1)
*/
testWord(sp, "economtric", "economic");
testWord(sp, "embaras", "embargo");
testWord(sp, "colate", "coat");
testWord(sp, "orentated", "orentated");
testWord(sp, "unequivocaly", "unequivocal");
testWord(sp, "generataed", "generate");
testWord(sp, "guidlines", "guideline");
}
private static void runTestPT()
{
//string trainFilePath = @"..\..\trainFiles\big.txt";
string trainFilePath = @"D:\Projectos_casa\Spell_Checker\ptwiki-20160601-pages-meta-current1.xml\ptwiki-20160601-pages-meta-current1.xml.001";
TweakedPeterNorvigSpellChecker sp = new TweakedPeterNorvigSpellChecker(Utils.Language.Portuguese);
sp.CurrentLang = Utils.Language.English;
sp.CurrentLang = Utils.Language.Portuguese;
sp.trainFromTextFile(Utils.Language.Portuguese, trainFilePath);
testWord(sp, "diaa", "dia");
int counts = 0;
string word = "dia";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
word = "dias";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
testWord(sp, "bondaide", "bondade");
testWord(sp, "cançaço", "cansaço");
testWord(sp, "feelizz", "feliz");
testWord(sp, "contenteee", "contente");
testWord(sp, "diz-mee", "diz-me");
testWord(sp, "plavras", "palavras");
testWord(sp, "pnoto", "ponto");
testWord(sp, "oje", "hoje");
testWord(sp, "trabalhoss", "trabalho");
testWord(sp, "iram", "irão");
}
private static void runTestWordListPT()
{
// string trainFilePath = @"..\..\trainFiles\big.txt";
string trainWordListFilePath = @"D:\Projectos_casa\Spell_Checker\WordLists_PT\europarl-v7.pt-en.pt_WordList_158325_.txt";
TweakedPeterNorvigSpellChecker sp = new TweakedPeterNorvigSpellChecker(Utils.Language.Portuguese);
sp.CurrentLang = Utils.Language.English;
sp.CurrentLang = Utils.Language.Portuguese;
bool withFreq = true;
sp.trainFromWordListFile(Utils.Language.Portuguese, trainWordListFilePath, withFreq);
testWord(sp, "diaa", "dia");
int counts = 0;
string word = "dia";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
word = "dias";
if (sp.dataOnWord(word, out counts))
Console.WriteLine($"word: {word} counts: {counts}");
testWord(sp, "bondaide", "bondade");
testWord(sp, "cançaço", "cansaço");
testWord(sp, "feelizz", "feliz");
testWord(sp, "contenteee", "contente");
testWord(sp, "diz-mee", "diz-me");
testWord(sp, "plavras", "palavras");
testWord(sp, "pnoto", "ponto");
testWord(sp, "oje", "hoje");
testWord(sp, "trabalhoss", "trabalho");
testWord(sp, "iram", "irão");
}
private static void testWord(TweakedPeterNorvigSpellChecker sp, string word, string expected)
{
bool wordIsCorrect;
List<WordFreq> wordsList = sp.correct(word, out wordIsCorrect);
string sugestedWord = "";
if (wordsList.Count > 0)
sugestedWord = wordsList[0].Word;
Console.WriteLine($"correct('{word}') => '{sugestedWord}'; expected '{expected}'");
}
}
internal class SpellCheckerConsoleInterface
{
internal SpellCheckerConsoleInterface()
{
}
internal void startConsole()
{
TweakedPeterNorvigSpellChecker tsc = new TweakedPeterNorvigSpellChecker(Utils.Language.Portuguese);
tsc.CurrentLang = Utils.Language.Portuguese;
string trainWordListFilePath = @"D:\Projectos_casa\Spell_Checker\WordLists_PT\europarl-v7.pt-en.pt_WordList_158325_.txt";
bool withFreq = true;
tsc.trainFromWordListFile(Utils.Language.Portuguese, trainWordListFilePath, withFreq);
Console.WriteLine("\n\nStarting Spell Checker console type \"quit\" to exit.");
string word;
do
{
Console.Write("\nWord: ");
word = Console.ReadLine().Trim();
if (word != "" && word.ToLower() != "quit")
{
string firstWord = word.Split(' ')[0];
bool wordIsCorrect;
List<WordFreq> correctedWordsList = tsc.correct(firstWord, out wordIsCorrect);
if (wordIsCorrect)
Console.WriteLine($"Word is Correct!");
else
{
Console.WriteLine($"Correct word: {TweakedPeterNorvigSpellChecker.wordListToString(correctedWordsList)}");
}
}
} while (word.ToLower() != "quit");
Console.WriteLine("\n\n Quiting the program!");
}
}
public static class ExtensionToHashSet
{
public static bool AddRange<T>(this HashSet<T> @this, IEnumerable<T> items)
{
bool allAdded = true;
foreach (T item in items)
{
allAdded &= @this.Add(item);
}
return allAdded;
}
}
internal class WordFreq
{
internal string Word { get; set; }
internal int Count { get; set; }
internal WordFreq(string word, int count )
{
this.Word = word;
this.Count = count;
}
public override string ToString()
{
return $"{Word}:{Count}";
}
internal void incrementCount()
{
Count++;
}
}
}