-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.2_pyahocorasick.py
329 lines (245 loc) · 7.69 KB
/
1.2_pyahocorasick.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
from collections import deque
nil = object() # used to distinguish from None
class TrieNode(object):
"""
Node of trie/Aho-Corasick automaton
"""
__slots__ = ['char', 'output', 'fail', 'children']
def __init__(self, char):
"""
Constructs an empty node
"""
self.char = char # character
self.output = nil # an output function for this node
self.fail = nil # fail link used by Aho-Corasick automaton
self.children = {} # children
def __repr__(self):
"""
Textual representation of node.
"""
if self.output is not nil:
return "<TrieNode '%s' '%s'>" % (self.char, self.output)
else:
return "<TrieNode '%s'>" % self.char
class Trie(object):
"""
Trie/Aho-Corasick automaton.
"""
def __init__(self):
"""
Construct an empty trie
"""
self.root = TrieNode('')
def __get_node(self, word):
"""
Private function retrieving a final node of trie
for given word
Returns node or None, if the trie doesn't contain the word.
"""
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
return None
return node
def get(self, word, default=nil):
"""
Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError.
"""
node = self.__get_node(word)
output = nil
if node:
output = node.output
if output is nil:
if default is nil:
raise KeyError("no key '%s'" % word)
else:
return default
else:
return output
def keys(self):
"""
Generator returning all keys (i.e. word) stored in trie
"""
for key, _ in self.items():
yield key
def values(self):
"""
Generator returning all values associated with words stored in a trie.
"""
for _, value in self.items():
yield value
def items(self):
"""
Generator returning all keys and values stored in a trie.
"""
L = []
def aux(node, s):
s = s + node.char
if node.output is not nil:
L.append((s, node.output))
for child in node.children.values():
if child is not node:
aux(child, s)
aux(self.root, '')
return iter(L)
def __len__(self):
"""
Calculates number of words in a trie.
"""
stack = deque()
stack.append(self.root)
n = 0
while stack:
node = stack.pop()
if node.output is not nil:
n += 1
for child in node.children.values():
stack.append(child)
return n
def add_word(self, word, value):
"""
Adds word and associated value.
If word already exists, its value is replaced.
"""
if not word:
return
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
n = TrieNode(c)
node.children[c] = n
node = n
node.output = value
def clear(self):
"""
Clears trie.
"""
self.root = TrieNode('')
def exists(self, word):
"""
Checks if whole word is present in the trie.
"""
node = self.__get_node(word)
if node:
return bool(node.output != nil)
else:
return False
def match(self, word):
"""
Checks if word is a prefix of any existing word in the trie.
"""
return (self.__get_node(word) is not None)
def make_automaton(self):
"""
Converts trie to Aho-Corasick automaton.
"""
queue = deque()
# 1.
for i in range(256):
c = chr(i)
if c in self.root.children:
node = self.root.children[c]
node.fail = self.root # f(s) = 0
queue.append(node)
else:
self.root.children[c] = self.root
# 2.
while queue:
r = queue.popleft()
for node in r.children.values():
queue.append(node)
state = r.fail
while node.char not in state.children:
state = state.fail
node.fail = state.children.get(node.char, self.root)
def iter(self, string):
"""
Generator performs Aho-Corasick search string algorithm, yielding
tuples containing two values:
- position in string
- outputs associated with matched strings
"""
state = self.root
for index, c in enumerate(string):
while c not in state.children:
state = state.fail
state = state.children.get(c, self.root)
tmp = state
output = []
while tmp is not nil:
if tmp.output is not nil:
output.append(tmp.output)
tmp = tmp.fail
if output:
yield (index, output)
def iter_long(self, string):
"""
Generator performs a modified Aho-Corasick search string algorithm,
which maches only the longest word.
"""
state = self.root
last = None
index = 0
while index < len(string):
c = string[index]
if c in state.children:
state = state.children[c]
if state.output is not nil:
# save the last node on the path
last = (state.output, index)
index += 1
else:
if last:
# return the saved match
yield last
# and start over, as we don't want overlapped results
# Note: this leads to quadratic complexity in the worst case
index = last[1] + 1
state = self.root
last = None
else:
# if no output, perform classic Aho-Corasick algorithm
while c not in state.children:
state = state.fail
# corner case
if last:
yield last
def find_all(self, string, callback):
"""
Wrapper on iter method, callback gets an iterator result
"""
for index, output in self.iter(string):
callback(index, output)
if __name__ == '__main__':
def demo():
words = "he hers his she hi him man".split()
t = Trie();
for w in words:
t.add_word(w, w)
s = "he rshershidamanza "
t.make_automaton()
for res in t.items():
print(res)
for res in t.iter(s):
print
print('%s' % s)
pos, matches = res
for fragment in matches:
print('%s%s' % ((pos - len(fragment) + 1)*' ', fragment))
demo()
def bug():
patterns = ['GT-C3303','SAMSUNG-GT-C3303K/']
text = 'SAMSUNG-GT-C3303i/1.0 NetFront/3.5 Profile/MIDP-2.0 Configuration/CLDC-1.1'
t = Trie()
for pattern in patterns:
ret = t.add_word(pattern, (0, pattern))
t.make_automaton()
res = list(t.iter(text))
assert len(res) == 1, 'failed'
bug()