-
Notifications
You must be signed in to change notification settings - Fork 303
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Python implementation of Aho-Corasick string matching | ||
FAIL = -1 | ||
|
||
def aho_corasick(string, keywords): | ||
transitions = {} | ||
outputs = {} | ||
fails = {} | ||
|
||
new_state = 0 | ||
|
||
for keyword in keywords: | ||
state = 0 | ||
|
||
for j, char in enumerate(keyword): | ||
res = transitions.get((state, char), FAIL) | ||
if res == FAIL: | ||
break | ||
state = res | ||
|
||
for char in keyword[j:]: | ||
new_state += 1 | ||
transitions[(state, char)] = new_state | ||
state = new_state | ||
|
||
outputs[state] = [keyword] | ||
|
||
queue = [] | ||
for (from_state, char), to_state in transitions.items(): | ||
if from_state == 0 and to_state != 0: | ||
queue.append(to_state) | ||
fails[to_state] = 0 | ||
|
||
while queue: | ||
r = queue.pop(0) | ||
for (from_state, char), to_state in transitions.items(): | ||
if from_state == r: | ||
queue.append(to_state) | ||
state = fails[from_state] | ||
|
||
while True: | ||
res = transitions.get((state, char), state and FAIL) | ||
if res != FAIL: | ||
break | ||
state = fails[state] | ||
|
||
failure = transitions.get((state, char), state and FAIL) | ||
fails[to_state] = failure | ||
outputs.setdefault(to_state, []).extend( | ||
outputs.get(failure, [])) | ||
|
||
state = 0 | ||
results = [] | ||
for i, char in enumerate(string): | ||
while True: | ||
res = transitions.get((state, char), state and FAIL) | ||
if res != FAIL: | ||
state = res | ||
break | ||
state = fails[state] | ||
|
||
for match in outputs.get(state, ()): | ||
pos = i - len(match) + 1 | ||
results.append((pos, match)) | ||
|
||
return results |