-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspellcheck.py
More file actions
177 lines (145 loc) · 4.87 KB
/
spellcheck.py
File metadata and controls
177 lines (145 loc) · 4.87 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
from operator import itemgetter
from .game import PGZeroGame, positional_parameters
def distance(a, b):
"""Compute the distance between a and b.
This is based on Damerau-Levenshtein distance, but we modify the cost
of some edits, like insertion or removal of '_', or capitalisation changes.
"""
d = {}
la = len(a)
lb = len(b)
for i in range(la + 1):
d[i, 0] = i
for j in range(1, lb + 1):
d[0, j] = j
for i, ca in enumerate(a, start=1):
for j, cb in enumerate(b, start=1):
cost = int(ca != cb)
if ca.lower() == cb.lower():
subst_cost = 0
else:
subst_cost = 1.25 * cost
insertion_cost = 0.7 if cb == '_' else 1.0
deletion_cost = 0.7 if ca == '_' else 1.0
d[i, j] = min(
d[i - 1, j] + deletion_cost, # deletion
d[i, j - 1] + insertion_cost, # insertion
d[i - 1, j - 1] + subst_cost, # substitution
)
if i > 1 and j > 1 and ca == b[j - 2] and a[i - 2] == cb:
d[i, j] = min(
d[i, j],
d[i - 2, j - 2] + cost # transposition
)
return d[la, lb]
def suggest(word, candidates):
"""Suggest good candidates as corrections for the given word.
Suggestions will be ordered from best to worst.
"""
candidates_with_score = [(c, distance(word, c)) for c in candidates]
good_candidates = [(c, d) for c, d in candidates_with_score if d < 2.6]
good_candidates.sort(key=itemgetter(1))
# print(word, good_candidates)
return [c for c, d in good_candidates]
def compare(have, want):
"""Compare a set of names we have (from user input) to those we want.
This is a greedy algorithm that will take the best answer for each word
in have in turn.
"""
want = set(want)
have = set(have)
matched = want & have
want -= matched
have -= matched
for w in have:
suggestions = suggest(w, want)
if suggestions:
s = suggestions[0]
yield w, s
want.discard(s)
# The list of hooks we support
HOOKS = [
'draw',
'update',
] + list(PGZeroGame.EVENT_HANDLERS.values())
# The list of magic module-level constants
CONSTS = [
'TITLE',
'WIDTH',
'HEIGHT',
'ICON'
]
# Available parameters for each hook
# NB. update() takes one or zero positional parameter but we don't constrain
# the name.
#
# FIXME: These are from the documentation; there could be some missing here
VALID_PARAMS = {
'on_mouse_down': ['pos', 'button'],
'on_mouse_up': ['pos', 'button'],
'on_mouse_move': ['pos', 'buttons', 'rel'],
'on_key_up': ['key', 'mod'],
'on_key_down': ['unicode', 'key', 'mod'],
'draw': [],
'on_music_end': [],
}
class InvalidParameter(Exception):
"""A parameter to a hook was invalid."""
class SpellCheckResult:
def warn(self, msg, found, suggestion):
print(msg.format(
found=found,
suggestion=suggestion
))
def error(self, msg, found, suggestion):
raise InvalidParameter(msg.format(
found=found,
suggestion=suggestion
))
def spellcheck(namespace, result=SpellCheckResult()):
"""Spell check the names in the given module.
Where hooks are found, validate their positional parameters and offer
suggestions where mispelled.
"""
funcs = {}
consts = []
for name, val in namespace.items():
if callable(val) and not isinstance(val, type):
funcs[name] = val
elif isinstance(val, (str, int)):
consts.append(name)
for found, suggestion in compare(funcs, HOOKS):
result.warn(
"Warning: found function named {found}: "
"did you mean {suggestion}?",
found, suggestion
)
for found, suggestion in compare(consts, CONSTS):
result.warn(
"Warning: found constant named {found}: "
"did you mean {suggestion}?",
found, suggestion
)
for name, handler in funcs.items():
try:
valid = VALID_PARAMS[name]
except KeyError:
continue
else:
param_names = positional_parameters(handler)
for param in param_names:
if param in valid:
continue
suggestions = suggest(param, valid)
if suggestions:
result.error(
"%s() hook accepts no parameter {found}; "
"did you mean {suggestion}?" % name,
param,
suggestions[0]
)
else:
result.error(
"%s() hook accepts no parameter {found}" % name,
param, None
)