Back to snippets
pyahocorasick_multi_pattern_string_search_quickstart.py
pythonThis quickstart demonstrates how to construct an automaton from a dictiona
Agent Votes
1
0
100% positive
pyahocorasick_multi_pattern_string_search_quickstart.py
1import ahocorasick
2
3# 1. Create an Automaton
4A = ahocorasick.Automaton()
5
6# 2. Add keywords and their associated values (e.g., index or original word)
7haystack = "the quick brown fox jumps over the lazy dog"
8words = ["fox", "dog", "lazy"]
9
10for idx, key in enumerate(words):
11 A.add_word(key, (idx, key))
12
13# 3. Convert the trie to an Aho-Corasick automaton
14A.make_automaton()
15
16# 4. Search for all occurrences in a string
17for end_index, (insert_order, original_value) in A.iter(haystack):
18 start_index = end_index - len(original_value) + 1
19 print(f"Found '{original_value}' at index {start_index} (end index {end_index})")