forked from dantman/pywikia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spellcheck.py
555 lines (524 loc) · 20.5 KB
/
spellcheck.py
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
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
This bot spellchecks Wikipedia pages. It is very simple, only checking
whether a word, stripped to its 'essence' is in the list or not, it does
not do any grammar checking or such. It can be used in four ways:
spellcheck.py Title
Check a single page; after this the bot will ask whether you want to
check another page
spellcheck.py -start:Title
Go through the wiki, starting at title 'Title'.
spellcheck.py -newpages
Go through the pages on [[Special:Newpages]]
spellcheck.py -longpages
Go through the pages on [[Special:Longpages]]
For each unknown word, you get a couple of options:
numbered options: replace by known alternatives
a: This word is correct; add it to the list of known words
c: The uncapitalized form of this word is correct; add it
i: Do not edit this word, but do also not add it to the list
p: Do not edit this word, and consider it correct for this page only
r: Replace the word, and add the replacement as a known alternative
s: Replace the word, but do not add the replacement
*: Edit the page using the gui
g: Give a list of 'guessed' words, which are similar to the given one
x: Ignore this word, and do not check the rest of the page
When the bot is ended, it will save the extensions to its word list;
there is one word list for each language.
The bot does not rely on Latin script, but does rely on Latin punctuation.
It is therefore expected to work on for example Russian and Korean, but not
on for example Japanese.
Command-line options:
-html change HTML-entities like ü into their respective letters.
This is done both before and after the normal check.
-rebuild save the complete wordlist, not just the changes, removing the
old wordlist.
-noname skip all words that start with a capital
-checklang:xx use the file for language xx: instead of that for my local
language; for example on simple: one would use the language
file of en:
-knownonly only check words that have been marked as a mis-spelling in
the spelling list; words that are not on the list are skipped
-knownplus finds words in the same way as knownonly, but once a word to
be changed has been found, also goes through the rest of the
page.
"""
#
# (C) Andre Engels, 2005
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
import re, sys
import wikipedia, pagegenerators
import string, codecs
msg={
'ar':u'تدقيق إملائي بمساعدة البوت',
'en':u'Bot-aided spell checker',
'es':u'Bot asistido de correción ortográfica',
'fr':u'Correction orthographique par robot',
'he':u'בדיקת איות באמצעות בוט',
'ia':u'Correction de orthographia per robot',
'nl':u'Spellingscontrole',
'pl':u'Wspomagane przez robota sprawdzanie pisowni',
'pt':u'Bot de correção ortográfica',
}
class SpecialTerm(object):
def __init__(self,text):
self.style = text
def distance(a,b):
# Calculates the Levenshtein distance between a and b.
# That is, the number of edits needed to change one into
# the other, where one edit is the addition, removal or
# change of a single character.
# Copied from Magnus Lie Hetland at http://hetland.org/python/
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1,m+1):
previous, current = current, [i]+[0]*m
for j in range(1,n+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n]
def getalternatives(string):
# Find possible correct words for the incorrect word string
basetext = wikipedia.input(u"Give a text that should occur in the words to be checked.\nYou can choose to give no text, but this will make searching slow:")
basetext = basetext.lower()
simwords = {}
for i in xrange(11):
simwords[i] = []
for alt in knownwords.keys():
if basetext:
if basetext not in alt.lower() == -1:
dothis = False
else:
dothis = True
else: dothis = True
if dothis:
diff = distance(string,alt)
if diff < 11:
if knownwords[alt] == alt:
simwords[diff] += [alt]
else:
simwords[diff] += knownwords[alt]
posswords = []
for i in xrange(11):
if not simwords[i] in posswords:
posswords += simwords[i]
return posswords[:30]
def uncap(string):
# uncapitalize the first word of the string
if len(string) > 1:
return string[0].lower()+string[1:]
else:
return string.lower()
def cap(string):
# uncapitalize the first word of the string
return string[0].upper()+string[1:]
def askAlternative(word,context=None):
correct = None
wikipedia.output(u"="*60)
wikipedia.output(u"Found unknown word '%s'"%word)
if context:
wikipedia.output(u"Context:")
wikipedia.output(u""+context)
wikipedia.output(u"-"*60)
while not correct:
for i in xrange(len(Word(word).getAlternatives())):
wikipedia.output(u"%s: Replace by '%s'"%(i+1,Word(word).getAlternatives()[i].replace('_',' ')))
wikipedia.output(u"a: Add '%s' as correct"%word)
if word[0].isupper():
wikipedia.output(u"c: Add '%s' as correct"%(uncap(word)))
wikipedia.output(u"i: Ignore once (default)")
wikipedia.output(u"p: Ignore on this page")
wikipedia.output(u"r: Replace text")
wikipedia.output(u"s: Replace text, but do not save as alternative")
wikipedia.output(u"g: Guess (give me a list of similar words)")
wikipedia.output(u"*: Edit by hand")
wikipedia.output(u"x: Do not check the rest of this page")
answer = wikipedia.input(u":")
if answer == "": answer = "i"
if answer in "aAiIpP":
correct = word
if answer in "aA":
knownwords[word] = word
newwords.append(word)
elif answer in "pP":
pageskip.append(word)
elif answer in "rRsS":
correct = wikipedia.input(u"What should I replace it by?")
if answer in "rR":
if correct_html_codes:
correct = removeHTML(correct)
if correct != cap(word) and correct != uncap(word) and correct != word:
try:
knownwords[word] += [correct.replace(' ','_')]
except KeyError:
knownwords[word] = [correct.replace(' ','_')]
newwords.append(word)
knownwords[correct] = correct
newwords.append(correct)
elif answer in "cC" and word[0].isupper():
correct = word
knownwords[uncap(word)] = uncap(word)
newwords.append(uncap(word))
elif answer in "gG":
possible = getalternatives(word)
if possible:
print "Found alternatives:"
for pos in possible:
wikipedia.output(" %s"%pos)
else:
print "No similar words found."
elif answer=="*":
correct = edit
elif answer=="x":
correct = endpage
else:
for i in xrange(len(Word(word).getAlternatives())):
if answer == str(i+1):
correct = Word(word).getAlternatives()[i].replace('_',' ')
return correct
def removeHTML(page):
# TODO: Consider removing this; this stuff can be done by cosmetic_changes.py
result = page
result = result.replace('Ä',u'Ä')
result = result.replace('ä',u'ä')
result = result.replace('Ë',u'Ë')
result = result.replace('ë',u'ë')
result = result.replace('Ï',u'Ï')
result = result.replace('ï',u'ï')
result = result.replace('Ö',u'Ö')
result = result.replace('ö',u'ö')
result = result.replace('Ü',u'Ü')
result = result.replace('ü',u'ü')
result = result.replace('Á',u'Á')
result = result.replace('á',u'á')
result = result.replace('É',u'É')
result = result.replace('é',u'é')
result = result.replace('Í',u'Í')
result = result.replace('í',u'í')
result = result.replace('Ó',u'Ó')
result = result.replace('ó',u'ó')
result = result.replace('Ú',u'Ú')
result = result.replace('ú',u'ú')
result = result.replace('À',u'À')
result = result.replace('à',u'à')
result = result.replace('È',u'È')
result = result.replace('è',u'è')
result = result.replace('Ì',u'Ì')
result = result.replace('ì',u'ì')
result = result.replace('Ò',u'Ò')
result = result.replace('ò',u'ò')
result = result.replace('Ù',u'Ù')
result = result.replace('ù',u'ù')
result = result.replace('Â',u'Â')
result = result.replace('â',u'â')
result = result.replace('Ê',u'Ê')
result = result.replace('ê',u'ê')
result = result.replace('Î',u'Î')
result = result.replace('î',u'î')
result = result.replace('Ô',u'Ô')
result = result.replace('ô',u'ô')
result = result.replace('Û',u'Û')
result = result.replace('û',u'û')
result = result.replace('Å',u'Å')
result = result.replace('å',u'å')
result = result.replace('°',u'°')
return result
def spellcheck(page, checknames = True, knownonly = False):
pageskip = []
text = page
if correct_html_codes:
text = removeHTML(text)
loc = 0
while True:
wordsearch = re.compile(r'([\s\=\<\>\_]*)([^\s\=\<\>\_]+)')
match = wordsearch.search(text,loc)
if not match:
# No more words on this page
break
loc += len(match.group(1))
bigword = Word(match.group(2))
smallword = bigword.derive()
if not Word(smallword).isCorrect(checkalternative = knownonly) and (checknames or not smallword[0].isupper()):
replacement = askAlternative(smallword,context=text[max(0,loc-40):loc+len(match.group(2))+40])
if replacement == edit:
import editarticle
editor = editarticle.TextEditor()
# TODO: Don't know to which index to jump
newtxt = editor.edit(text, jumpIndex = 0, highlight = smallword)
if newtxt:
text = newtxt
elif replacement == endpage:
loc = len(text)
else:
replacement = bigword.replace(replacement)
text = text[:loc] + replacement + text[loc+len(match.group(2)):]
loc += len(replacement)
if knownonly == 'plus' and text != page:
knownonly = False
loc = 0
else:
loc += len(match.group(2))
if correct_html_codes:
text = removeHTML(text)
pageskip = []
return text
class Word(object):
def __init__(self,text):
self.word = text
def __str__(self):
return self.word
def __cmp__(self,other):
return self.word.__cmp__(str(other))
def derive(self):
# Get the short form of the word, without punctuation, square
# brackets etcetera
shortword = self.word
# Remove all words of the form [[something:something - these are
# usually interwiki links or category links
if shortword.rfind(':') != -1:
if -1 < shortword.rfind('[[') < shortword.rfind(':'):
shortword = ""
# Remove barred links
if shortword.rfind('|') != -1:
if -1 < shortword.rfind('[[') < shortword.rfind('|'):
shortword = shortword[:shortword.rfind('[[')] + shortword[shortword.rfind('|')+1:]
else:
shortword = shortword[shortword.rfind('|')+1:]
shortword = shortword.replace('[','')
shortword = shortword.replace(']','')
# Remove non-alphanumerical characters at the start
try:
while shortword[0] in string.punctuation:
shortword=shortword[1:]
except IndexError:
return ""
# Remove non-alphanumerical characters at the end; no need for the
# try here because if things go wrong here, they should have gone
# wrong before
while shortword[-1] in string.punctuation:
shortword=shortword[:-1]
# Do not check URLs
if shortword.startswith("http://"):
shortword=""
# Do not check 'words' with only numerical characters
number = True
for i in xrange(len(shortword)):
if not (shortword[i] in string.punctuation or shortword[i] in string.digits):
number = False
if number:
shortword = ""
return shortword
def replace(self,rep):
# Replace the short form by 'rep'. Keeping simple for now - if the
# short form is part of the long form, replace it. If it is not, ask
# the user
if rep == self.derive():
return self.word
if self.derive() not in self.word:
return wikipedia.input(u"Please give the result of replacing %s by %s in %s:"%(self.derive(),rep,self.word))
return self.word.replace(self.derive(),rep)
def isCorrect(self,checkalternative = False):
# If checkalternative is True, the word will only be found incorrect if
# it is on the spelling list as a spelling error. Otherwise it will
# be found incorrect if it is not on the list as a correctly spelled word.
if self.word == "":
return True
if self.word in pageskip:
return True
try:
if knownwords[self.word] == self.word:
return True
else:
return False
except KeyError:
pass
if self.word != uncap(self.word):
return Word(uncap(self.word)).isCorrect(checkalternative = checkalternative)
else:
if checkalternative:
if checklang == 'nl' and self.word.endswith("'s"):
# often these are incorrect (English-style) possessives
return False
if self.word != cap(self.word):
if Word(cap(self.word)).isCorrect():
return False
else:
return True
else:
return True
else:
return False
def getAlternatives(self):
alts = []
if self.word[0].islower():
if Word(cap(self.word)).isCorrect():
alts = [cap(self.word)]
try:
alts += knownwords[self.word]
except KeyError:
pass
if self.word[0].isupper():
try:
alts += [cap(w) for w in knownwords[uncap(self.word)]]
except KeyError:
pass
return alts
def declare_correct(self):
knownwords[self.word] = self.word
def declare_alternative(self,alt):
if not alt in knownwords[self.word]:
knownwords[self.word].append(word)
newwords.append(self.word)
return self.alternatives
try:
pageskip = []
edit = SpecialTerm("edit")
endpage = SpecialTerm("end page")
title = []
knownwords = {}
newwords = []
start = None
newpages = False
longpages = False
correct_html_codes = False
rebuild = False
checknames = True
checklang = None
knownonly = False
for arg in wikipedia.handleArgs():
if arg.startswith("-start:"):
start = arg[7:]
elif arg.startswith("-newpages"):
newpages = True
elif arg.startswith("-longpages"):
longpages = True
elif arg.startswith("-html"):
correct_html_codes = True
elif arg.startswith("-rebuild"):
rebuild = True
elif arg.startswith("-noname"):
checknames = False
elif arg.startswith("-checklang:"):
checklang = arg[11:]
elif arg.startswith("-knownonly"):
knownonly = True
elif arg.startswith("-knownplus"):
knownonly = 'plus'
else:
title.append(arg)
mysite = wikipedia.getSite()
if not checklang:
checklang = mysite.language()
wikipedia.setAction(wikipedia.translate(mysite,msg))
filename = wikipedia.config.datafilepath('spelling',
'spelling-' + checklang + '.txt')
print "Getting wordlist"
try:
f = codecs.open(filename, 'r', encoding = mysite.encoding())
for line in f.readlines():
# remove trailing newlines and carriage returns
try:
while line[-1] in ['\n', '\r']:
line = line[:-1]
except IndexError:
pass
#skip empty lines
if line != '':
if line[0] == "1":
word = line[2:]
knownwords[word] = word
else:
line = line.split(' ')
word = line[1]
knownwords[word] = line[2:]
for word2 in line[2:]:
if not '_' in word2:
knownwords[word2] = word2
f.close()
except IOError:
print "Warning! There is no wordlist for your language!"
else:
print "Wordlist successfully loaded."
# This is a purely interactive bot, we therefore do not want to put-throttle
wikipedia.put_throttle.setDelay(1)
except:
wikipedia.stopme()
raise
try:
if newpages:
for (page, date, length, loggedIn, user, comment) in wikipedia.getSite().newpages(1000):
try:
text = page.get()
except wikipedia.Error:
pass
else:
text = spellcheck(text,checknames=checknames,knownonly=knownonly)
if text != page.get():
page.put(text)
elif start:
for page in pagegenerators.PreloadingGenerator(pagegenerators.AllpagesPageGenerator(start=start,includeredirects=False)):
try:
text = page.get()
except wikipedia.Error:
pass
else:
text = spellcheck(text,checknames=checknames,knownonly=knownonly)
if text != page.get():
page.put(text)
if longpages:
for (page, length) in wikipedia.getSite().longpages(500):
try:
text = page.get()
except wikipedia.Error:
pass
else:
text = spellcheck(text, checknames = checknames,knownonly=knownonly)
if text != page.get():
page.put(text)
else:
title = ' '.join(title)
while title != '':
try:
page = wikipedia.Page(mysite,title)
text = page.get()
except wikipedia.NoPage:
print "Page does not exist."
except wikipedia.IsRedirectPage:
print "Page is a redirect page"
else:
text = spellcheck(text,knownonly=knownonly)
if text != page.get():
page.put(text)
title = wikipedia.input(u"Which page to check now? (enter to stop)")
finally:
wikipedia.stopme()
filename = wikipedia.config.datafilepath('spelling',
'spelling-' + checklang + '.txt')
if rebuild:
list = knownwords.keys()
list.sort()
f = codecs.open(filename, 'w', encoding = mysite.encoding())
else:
list = newwords
f = codecs.open(filename, 'a', encoding = mysite.encoding())
for word in list:
if Word(word).isCorrect():
if word != uncap(word):
if Word(uncap(word)).isCorrect():
# Capitalized form of a word that is in the list uncapitalized
continue
f.write("1 %s\n"%word)
else:
f.write("0 %s %s\n"%(word," ".join(knownwords[word])))
f.close()