en/NlpInPracticeCourse/2021/AutomaticCorrection: spell.py

File spell.py, 15.8 KB (added by Ales Horak, 20 months ago)
Line 
1"""Spelling Corrector.
2
3Copyright 2007 Peter Norvig.
4Open source code under MIT license: http://www.opensource.org/licenses/mit-license.php
5"""
6
7import re, collections
8
9def words(text): return re.findall('[a-z]+', text.lower()) 
10
11def train(features):
12    model = collections.defaultdict(lambda: 1)
13    for f in features:
14        model[f] += 1
15    return model
16
17NWORDS = train(words(file('big.txt').read()))
18
19alphabet = 'abcdefghijklmnopqrstuvwxyz'
20
21def edits1(word):
22   s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
23   deletes    = [a + b[1:] for a, b in s if b]
24   transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b)>1]
25   replaces   = [a + c + b[1:] for a, b in s for c in alphabet if b]
26   inserts    = [a + c + b     for a, b in s for c in alphabet]
27   return set(deletes + transposes + replaces + inserts)
28
29def known_edits2(word):
30    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
31
32def known(words): return set(w for w in words if w in NWORDS)
33
34def correct(word):
35    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
36    return max(candidates, key=NWORDS.get)
37
38################ Testing code from here on ################
39
40def spelltest(tests, bias=None, verbose=False):
41    import time
42    n, bad, unknown, start = 0, 0, 0, time.clock()
43    if bias:
44        # simulate we have larger model which contains +bias occurences of
45        # all tested words - just for an estimate of how a larger model
46        # would work
47        for target in tests: NWORDS[target] += bias
48    for target,wrongs in tests.items():
49        for wrong in wrongs.split():
50            n += 1
51            w = correct(wrong)
52            if w!=target:
53                bad += 1
54                unknown += (target not in NWORDS)
55                if verbose:
56                    print 'correct(%r) => %r (%d); expected %r (%d)' % (
57                        wrong, w, NWORDS[w] if w in NWORDS else 0, target, 
58                        NWORDS[target] if target in NWORDS else 0)
59    return dict(bad=bad, n=n, bias=bias, pct=int(100. - 100.*bad/n), 
60                unknown=unknown, secs=int(time.clock()-start) )
61
62tests1 = { 'access': 'acess', 'accessing': 'accesing', 'accommodation':
63'accomodation acommodation acomodation', 'account': 'acount', 'address':
64'adress adres', 'addressable': 'addresable', 'arranged': 'aranged arrainged',
65'arranging': 'arangeing', 'arrangement': 'arragment', 'articles': 'articals',
66'aunt': 'annt anut arnt', 'auxiliary': 'auxillary', 'available': 'avaible',
67'awful': 'awfall afful', 'basically': 'basicaly', 'beginning': 'begining',
68'benefit': 'benifit', 'benefits': 'benifits', 'between': 'beetween', 'bicycle':
69'bicycal bycicle bycycle', 'biscuits': 
70'biscits biscutes biscuts bisquits buiscits buiscuts', 'built': 'biult', 
71'cake': 'cak', 'career': 'carrer',
72'cemetery': 'cemetary semetary', 'centrally': 'centraly', 'certain': 'cirtain',
73'challenges': 'chalenges chalenges', 'chapter': 'chaper chaphter chaptur',
74'choice': 'choise', 'choosing': 'chosing', 'clerical': 'clearical',
75'committee': 'comittee', 'compare': 'compair', 'completely': 'completly',
76'consider': 'concider', 'considerable': 'conciderable', 'contented':
77'contenpted contende contended contentid', 'curtains': 
78'cartains certans courtens cuaritains curtans curtians curtions', 'decide': 'descide', 'decided':
79'descided', 'definitely': 'definately difinately', 'definition': 'defenition',
80'definitions': 'defenitions', 'description': 'discription', 'desiccate':
81'desicate dessicate dessiccate', 'diagrammatically': 'diagrammaticaally',
82'different': 'diffrent', 'driven': 'dirven', 'ecstasy': 'exstacy ecstacy',
83'embarrass': 'embaras embarass', 'establishing': 'astablishing establising',
84'experience': 'experance experiance', 'experiences': 'experances', 'extended':
85'extented', 'extremely': 'extreamly', 'fails': 'failes', 'families': 'familes',
86'february': 'febuary', 'further': 'futher', 'gallery': 'galery gallary gallerry gallrey', 
87'hierarchal': 'hierachial', 'hierarchy': 'hierchy', 'inconvenient':
88'inconvienient inconvient inconvinient', 'independent': 'independant independant',
89'initial': 'intial', 'initials': 'inetials inistals initails initals intials',
90'juice': 'guic juce jucie juise juse', 'latest': 'lates latets latiest latist', 
91'laugh': 'lagh lauf laught lugh', 'level': 'leval',
92'levels': 'levals', 'liaison': 'liaision liason', 'lieu': 'liew', 'literature':
93'litriture', 'loans': 'lones', 'locally': 'localy', 'magnificent': 
94'magnificnet magificent magnifcent magnifecent magnifiscant magnifisent magnificant',
95'management': 'managment', 'meant': 'ment', 'minuscule': 'miniscule',
96'minutes': 'muinets', 'monitoring': 'monitering', 'necessary': 
97'neccesary necesary neccesary necassary necassery neccasary', 'occurrence':
98'occurence occurence', 'often': 'ofen offen offten ofton', 'opposite': 
99'opisite oppasite oppesite oppisit oppisite opposit oppossite oppossitte', 'parallel': 
100'paralel paralell parrallel parralell parrallell', 'particular': 'particulaur',
101'perhaps': 'perhapse', 'personnel': 'personnell', 'planned': 'planed', 'poem':
102'poame', 'poems': 'poims pomes', 'poetry': 'poartry poertry poetre poety powetry', 
103'position': 'possition', 'possible': 'possable', 'pretend': 
104'pertend protend prtend pritend', 'problem': 'problam proble promblem proplen',
105'pronunciation': 'pronounciation', 'purple': 'perple perpul poarple',
106'questionnaire': 'questionaire', 'really': 'realy relley relly', 'receipt':
107'receit receite reciet recipt', 'receive': 'recieve', 'refreshment':
108'reafreshment refreshmant refresment refressmunt', 'remember': 'rember remeber rememmer rermember',
109'remind': 'remine remined', 'scarcely': 'scarcly scarecly scarely scarsely', 
110'scissors': 'scisors sissors', 'separate': 'seperate',
111'singular': 'singulaur', 'someone': 'somone', 'sources': 'sorces', 'southern':
112'southen', 'special': 'speaical specail specal speical', 'splendid': 
113'spledid splended splened splended', 'standardizing': 'stanerdizing', 'stomach': 
114'stomac stomache stomec stumache', 'supersede': 'supercede superceed', 'there': 'ther',
115'totally': 'totaly', 'transferred': 'transfred', 'transportability':
116'transportibility', 'triangular': 'triangulaur', 'understand': 'undersand undistand', 
117'unexpected': 'unexpcted unexpeted unexspected', 'unfortunately':
118'unfortunatly', 'unique': 'uneque', 'useful': 'usefull', 'valuable': 'valubale valuble', 
119'variable': 'varable', 'variant': 'vairiant', 'various': 'vairious',
120'visited': 'fisited viseted vistid vistied', 'visitors': 'vistors',
121'voluntary': 'volantry', 'voting': 'voteing', 'wanted': 'wantid wonted',
122'whether': 'wether', 'wrote': 'rote wote'}
123
124tests2 = {'forbidden': 'forbiden', 'decisions': 'deciscions descisions',
125'supposedly': 'supposidly', 'embellishing': 'embelishing', 'technique':
126'tecnique', 'permanently': 'perminantly', 'confirmation': 'confermation',
127'appointment': 'appoitment', 'progression': 'progresion', 'accompanying':
128'acompaning', 'applicable': 'aplicable', 'regained': 'regined', 'guidelines':
129'guidlines', 'surrounding': 'serounding', 'titles': 'tittles', 'unavailable':
130'unavailble', 'advantageous': 'advantageos', 'brief': 'brif', 'appeal':
131'apeal', 'consisting': 'consisiting', 'clerk': 'cleark clerck', 'component':
132'componant', 'favourable': 'faverable', 'separation': 'seperation', 'search':
133'serch', 'receive': 'recieve', 'employees': 'emploies', 'prior': 'piror',
134'resulting': 'reulting', 'suggestion': 'sugestion', 'opinion': 'oppinion',
135'cancellation': 'cancelation', 'criticism': 'citisum', 'useful': 'usful',
136'humour': 'humor', 'anomalies': 'anomolies', 'would': 'whould', 'doubt':
137'doupt', 'examination': 'eximination', 'therefore': 'therefoe', 'recommend':
138'recomend', 'separated': 'seperated', 'successful': 'sucssuful succesful',
139'apparent': 'apparant', 'occurred': 'occureed', 'particular': 'paerticulaur',
140'pivoting': 'pivting', 'announcing': 'anouncing', 'challenge': 'chalange',
141'arrangements': 'araingements', 'proportions': 'proprtions', 'organized':
142'oranised', 'accept': 'acept', 'dependence': 'dependance', 'unequalled':
143'unequaled', 'numbers': 'numbuers', 'sense': 'sence', 'conversely':
144'conversly', 'provide': 'provid', 'arrangement': 'arrangment',
145'responsibilities': 'responsiblities', 'fourth': 'forth', 'ordinary':
146'ordenary', 'description': 'desription descvription desacription',
147'inconceivable': 'inconcievable', 'data': 'dsata', 'register': 'rgister',
148'supervision': 'supervison', 'encompassing': 'encompasing', 'negligible':
149'negligable', 'allow': 'alow', 'operations': 'operatins', 'executed':
150'executted', 'interpretation': 'interpritation', 'hierarchy': 'heiarky',
151'indeed': 'indead', 'years': 'yesars', 'through': 'throut', 'committee':
152'committe', 'inquiries': 'equiries', 'before': 'befor', 'continued':
153'contuned', 'permanent': 'perminant', 'choose': 'chose', 'virtually':
154'vertually', 'correspondence': 'correspondance', 'eventually': 'eventully',
155'lonely': 'lonley', 'profession': 'preffeson', 'they': 'thay', 'now': 'noe',
156'desperately': 'despratly', 'university': 'unversity', 'adjournment':
157'adjurnment', 'possibilities': 'possablities', 'stopped': 'stoped', 'mean':
158'meen', 'weighted': 'wagted', 'adequately': 'adequattly', 'shown': 'hown',
159'matrix': 'matriiix', 'profit': 'proffit', 'encourage': 'encorage', 'collate':
160'colate', 'disaggregate': 'disaggreagte disaggreaget', 'receiving':
161'recieving reciving', 'proviso': 'provisoe', 'umbrella': 'umberalla', 'approached':
162'aproached', 'pleasant': 'plesent', 'difficulty': 'dificulty', 'appointments':
163'apointments', 'base': 'basse', 'conditioning': 'conditining', 'earliest':
164'earlyest', 'beginning': 'begining', 'universally': 'universaly',
165'unresolved': 'unresloved', 'length': 'lengh', 'exponentially':
166'exponentualy', 'utilized': 'utalised', 'set': 'et', 'surveys': 'servays',
167'families': 'familys', 'system': 'sysem', 'approximately': 'aproximatly',
168'their': 'ther', 'scheme': 'scheem', 'speaking': 'speeking', 'repetitive':
169'repetative', 'inefficient': 'ineffiect', 'geneva': 'geniva', 'exactly':
170'exsactly', 'immediate': 'imediate', 'appreciation': 'apreciation', 'luckily':
171'luckeley', 'eliminated': 'elimiated', 'believe': 'belive', 'appreciated':
172'apreciated', 'readjusted': 'reajusted', 'were': 'wer where', 'feeling':
173'fealing', 'and': 'anf', 'false': 'faulse', 'seen': 'seeen', 'interrogating':
174'interogationg', 'academically': 'academicly', 'relatively': 'relativly relitivly',
175'traditionally': 'traditionaly', 'studying': 'studing',
176'majority': 'majorty', 'build': 'biuld', 'aggravating': 'agravating',
177'transactions': 'trasactions', 'arguing': 'aurguing', 'sheets': 'sheertes',
178'successive': 'sucsesive sucessive', 'segment': 'segemnt', 'especially':
179'especaily', 'later': 'latter', 'senior': 'sienior', 'dragged': 'draged',
180'atmosphere': 'atmospher', 'drastically': 'drasticaly', 'particularly':
181'particulary', 'visitor': 'vistor', 'session': 'sesion', 'continually':
182'contually', 'availability': 'avaiblity', 'busy': 'buisy', 'parameters':
183'perametres', 'surroundings': 'suroundings seroundings', 'employed':
184'emploied', 'adequate': 'adiquate', 'handle': 'handel', 'means': 'meens',
185'familiar': 'familer', 'between': 'beeteen', 'overall': 'overal', 'timing':
186'timeing', 'committees': 'comittees commitees', 'queries': 'quies',
187'econometric': 'economtric', 'erroneous': 'errounous', 'decides': 'descides',
188'reference': 'refereence refference', 'intelligence': 'inteligence',
189'edition': 'ediion ediition', 'are': 'arte', 'apologies': 'appologies',
190'thermawear': 'thermawere thermawhere', 'techniques': 'tecniques',
191'voluntary': 'volantary', 'subsequent': 'subsequant subsiquent', 'currently':
192'curruntly', 'forecast': 'forcast', 'weapons': 'wepons', 'routine': 'rouint',
193'neither': 'niether', 'approach': 'aproach', 'available': 'availble',
194'recently': 'reciently', 'ability': 'ablity', 'nature': 'natior',
195'commercial': 'comersial', 'agencies': 'agences', 'however': 'howeverr',
196'suggested': 'sugested', 'career': 'carear', 'many': 'mony', 'annual':
197'anual', 'according': 'acording', 'receives': 'recives recieves',
198'interesting': 'intresting', 'expense': 'expence', 'relevant':
199'relavent relevaant', 'table': 'tasble', 'throughout': 'throuout', 'conference':
200'conferance', 'sensible': 'sensable', 'described': 'discribed describd',
201'union': 'unioun', 'interest': 'intrest', 'flexible': 'flexable', 'refered':
202'reffered', 'controlled': 'controled', 'sufficient': 'suficient',
203'dissension': 'desention', 'adaptable': 'adabtable', 'representative':
204'representitive', 'irrelevant': 'irrelavent', 'unnecessarily': 'unessasarily',
205'applied': 'upplied', 'apologised': 'appologised', 'these': 'thees thess',
206'choices': 'choises', 'will': 'wil', 'procedure': 'proceduer', 'shortened':
207'shortend', 'manually': 'manualy', 'disappointing': 'dissapoiting',
208'excessively': 'exessively', 'comments': 'coments', 'containing': 'containg',
209'develop': 'develope', 'credit': 'creadit', 'government': 'goverment',
210'acquaintances': 'aquantences', 'orientated': 'orentated', 'widely': 'widly',
211'advise': 'advice', 'difficult': 'dificult', 'investigated': 'investegated',
212'bonus': 'bonas', 'conceived': 'concieved', 'nationally': 'nationaly',
213'compared': 'comppared compased', 'moving': 'moveing', 'necessity':
214'nessesity', 'opportunity': 'oppertunity oppotunity opperttunity', 'thoughts':
215'thorts', 'equalled': 'equaled', 'variety': 'variatry', 'analysis':
216'analiss analsis analisis', 'patterns': 'pattarns', 'qualities': 'quaties', 'easily':
217'easyly', 'organization': 'oranisation oragnisation', 'the': 'thw hte thi',
218'corporate': 'corparate', 'composed': 'compossed', 'enormously': 'enomosly',
219'financially': 'financialy', 'functionally': 'functionaly', 'discipline':
220'disiplin', 'announcement': 'anouncement', 'progresses': 'progressess',
221'except': 'excxept', 'recommending': 'recomending', 'mathematically':
222'mathematicaly', 'source': 'sorce', 'combine': 'comibine', 'input': 'inut',
223'careers': 'currers carrers', 'resolved': 'resoved', 'demands': 'diemands',
224'unequivocally': 'unequivocaly', 'suffering': 'suufering', 'immediately':
225'imidatly imediatly', 'accepted': 'acepted', 'projects': 'projeccts',
226'necessary': 'necasery nessasary nessisary neccassary', 'journalism':
227'journaism', 'unnecessary': 'unessessay', 'night': 'nite', 'output':
228'oputput', 'security': 'seurity', 'essential': 'esential', 'beneficial':
229'benificial benficial', 'explaining': 'explaning', 'supplementary':
230'suplementary', 'questionnaire': 'questionare', 'employment': 'empolyment',
231'proceeding': 'proceding', 'decision': 'descisions descision', 'per': 'pere',
232'discretion': 'discresion', 'reaching': 'reching', 'analysed': 'analised',
233'expansion': 'expanion', 'although': 'athough', 'subtract': 'subtrcat',
234'analysing': 'aalysing', 'comparison': 'comparrison', 'months': 'monthes',
235'hierarchal': 'hierachial', 'misleading': 'missleading', 'commit': 'comit',
236'auguments': 'aurgument', 'within': 'withing', 'obtaining': 'optaning',
237'accounts': 'acounts', 'primarily': 'pimarily', 'operator': 'opertor',
238'accumulated': 'acumulated', 'extremely': 'extreemly', 'there': 'thear',
239'summarys': 'sumarys', 'analyse': 'analiss', 'understandable':
240'understadable', 'safeguard': 'safegaurd', 'consist': 'consisit',
241'declarations': 'declaratrions', 'minutes': 'muinutes muiuets', 'associated':
242'assosiated', 'accessibility': 'accessability', 'examine': 'examin',
243'surveying': 'servaying', 'politics': 'polatics', 'annoying': 'anoying',
244'again': 'agiin', 'assessing': 'accesing', 'ideally': 'idealy', 'scrutinized':
245'scrutiniesed', 'simular': 'similar', 'personnel': 'personel', 'whereas':
246'wheras', 'when': 'whn', 'geographically': 'goegraphicaly', 'gaining':
247'ganing', 'requested': 'rquested', 'separate': 'seporate', 'students':
248'studens', 'prepared': 'prepaired', 'generated': 'generataed', 'graphically':
249'graphicaly', 'suited': 'suted', 'variable': 'varible vaiable', 'building':
250'biulding', 'required': 'reequired', 'necessitates': 'nessisitates',
251'together': 'togehter', 'profits': 'proffits'}
252
253if __name__ == '__main__':
254    print "**** tests 1 - verbose ****"
255    print spelltest(tests1, verbose=True)
256    print "\n**** tests 2 - summary ****"
257    print spelltest(tests2)
258
259
260