Here is a Python implementation of Aho-Corasick algorithm for string matching:
main.py2078 chars62 lines
To use the Aho-Corasick algorithm for string matching with given keywords, you can simply call the build_trie
, build_failure
, and search_strings
functions as follows:
main.py336 chars7 lines
In the example code above, the keywords
list contains the target words (i.e. "he", "she", "his", and "hers") and the text
string represents the text to search for those words. The search_strings
function returns a list of tuples, where each tuple contains the starting index of a matched keyword and the corresponding node object in the trie.
gistlibby LogSnag