### Install pyahocorasick via pip Source: https://pyahocorasick.readthedocs.io/ Use this command to install the library from PyPi. ```bash pip install pyahocorasick ``` -------------------------------- ### Install pyahocorasick from source Source: https://pyahocorasick.readthedocs.io/ Use this command within the source directory to build and install the library. ```bash pip install . ``` -------------------------------- ### Install pyahocorasick Source: https://pyahocorasick.readthedocs.io/ Install the pyahocorasick library using pip. A C compiler is required. ```bash pip install pyahocorasick ``` -------------------------------- ### Wildcard Search Examples Source: https://pyahocorasick.readthedocs.io/ Demonstrates using wildcard characters in the `keys` method to match patterns. The wildcard character can be any character, and it's not possible to escape it. ```python automaton.keys("hi?", "?") # would match "him", "his" automaton.keys("XX?", "X") # would match "me?", "he?" or "it?" ``` -------------------------------- ### Run tests for pyahocorasick Source: https://pyahocorasick.readthedocs.io/ Use this command to install testing dependencies and execute the test suite. ```bash pip installe -e .[testing] && pytest -vvs ``` -------------------------------- ### get(key[, default]) Source: https://pyahocorasick.readthedocs.io/ Retrieves the value associated with a key. ```APIDOC ## get(key[, default]) ### Description Return the value associated with the key string. Raise a KeyError if the key is not found and no default is provided. ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve. - **default** (any) - Optional - Value to return if key is missing. ``` -------------------------------- ### Iterating with AutomatonSearchIter Source: https://pyahocorasick.readthedocs.io/ Shows how to use the `iter` method to get an iterator for matches and then use the `set` method of the iterator to process chunks of data from a stream. The `reset` parameter can be used to restart the search. ```python >>> it = A.iter(b"") >>> while True: ... buffer = receive(server_address, 4096) ... if not buffer: ... break ... it.set(buffer) ... for index, value in it: ... print(index, '=>', value) ``` ```python >>> for string in string_set: ... for index, value in A.iter(string) ... print(index, '=>', value) ``` ```python >>> it = A.iter(b"") >>> for string in string_set: ... it.set(it, True) ... for index, value in it: ... print(index, '=>', value) ``` -------------------------------- ### Get Aho-Corasick Automaton Statistics Source: https://pyahocorasick.readthedocs.io/ Retrieve detailed statistics about the Aho-Corasick automaton, including node counts, word counts, longest word length, link counts, and memory usage. This is helpful for understanding the automaton's structure and performance characteristics. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> A.add_word("he", None) True >>> A.add_word("her", None) True >>> A.add_word("hers", None) True >>> A.get_stats() {'nodes_count': 5, 'words_count': 3, 'longest_word': 4, 'links_count': 4, 'sizeof_node': 40, 'total_size': 232} ``` -------------------------------- ### Get Number of Distinct Keys in Trie Source: https://pyahocorasick.readthedocs.io/ Returns the total count of unique keys that have been added to the trie. This provides a quick way to determine the size of the trie. ```python import ahocorasick A = ahocorasick.Automaton() len(A) 0 A.add_word("python", 1) True len(A) 1 A.add_word("elephant", True) True len(A) 2 ``` -------------------------------- ### Automaton Initialization Source: https://pyahocorasick.readthedocs.io/ Shows different ways to initialize an Automaton instance with various value and key types. Use `STORE_ANY` for general objects, `STORE_INTS` for integers, `STORE_LENGTH` for string lengths, and `KEY_STRING` or `KEY_SEQUENCE` for key types. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> A >>> B = ahocorasick.Automaton(ahocorasick.STORE_ANY) >>> B >>> C = ahocorasick.Automaton(ahocorasick.STORE_INTS, ahocorasick.KEY_STRING) >>> C ``` -------------------------------- ### Prefix Key Search Source: https://pyahocorasick.readthedocs.io/ Demonstrates using the `keys` method to search for keys with specific prefixes, including exact length, at most prefix, and at least prefix matching. Useful for wildcard searches and prefix-based lookups. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> # add some key words to trie >>> for index, word in enumerate('cat catastropha rat rate bat'.split()): ... A.add_word(word, (index, word)) >>> # Search some prefix >>> list(A.keys('cat')) ['cat', 'catastropha'] >>> # Search with a wildcard: here '?' is used as a wildcard. You can use any character you like. >>> list(A.keys('?at', '?', ahocorasick.MATCH_EXACT_LENGTH)) ['bat', 'cat', 'rat'] >>> list(A.keys('?at?', '?', ahocorasick.MATCH_AT_MOST_PREFIX)) ['bat', 'cat', 'rat', 'rate'] >>> list(A.keys('?at?', '?', ahocorasick.MATCH_AT_LEAST_PREFIX)) ['rate'] ``` -------------------------------- ### Automaton Class Initialization Source: https://pyahocorasick.readthedocs.io/ Initializes a new Automaton instance with optional value and key type configurations. ```APIDOC ## Automaton([value_type], [key_type]) ### Description Create a new empty Automaton instance. Optionally specify the type of associated values and the type of keys. ### Parameters - **value_type** (constant) - Optional - One of ahocorasick.STORE_ANY, ahocorasick.STORE_INTS, or ahocorasick.STORE_LENGTH. - **key_type** (constant) - Optional - One of ahocorasick.KEY_STRING or ahocorasick.KEY_SEQUENCE. ``` -------------------------------- ### Automaton Constructor Source: https://pyahocorasick.readthedocs.io/ Initializes a new empty Automaton instance with optional value and key type configurations. ```APIDOC ## Automaton(value_type=ahocorasick.STORE_ANY, [key_type]) ### Description Create a new empty Automaton. Both `value_type` and `key_type` are optional. ### Parameters - **value_type** (constant) - Optional - One of: ahocorasick.STORE_ANY (default), ahocorasick.STORE_LENGTH, ahocorasick.STORE_INTS. - **key_type** (constant) - Optional - One of: ahocorasick.KEY_STRING (default), ahocorasick.KEY_SEQUENCE. ``` -------------------------------- ### Pickle and Unpickle Automaton Source: https://pyahocorasick.readthedocs.io/ Demonstrates how to serialize an automaton to a string using pickle.dumps() and deserialize it back using pickle.loads(). This allows for saving and reusing pre-built automata. ```python >>> import pickle >>> pickled = pickle.dumps(automaton) >>> B = pickle.loads(pickled) >>> B.get('he') (0, 'he') ``` -------------------------------- ### Saving Automaton with Custom Methods Source: https://pyahocorasick.readthedocs.io/ Demonstrates saving and loading an automaton using custom `save` and `load` methods, which can help overcome the high memory requirements of pickling. A callable is required for serializing/deserializing non-standard value types. ```python import ahocorasick import pickle # build automaton A = ahocorasick.Automaton() # ... A.add_data, A.make_automaton # save current state A.save(path, pickle.dumps) # load saved state B = ahocorasick.load(path, pickle.loads) ``` -------------------------------- ### Saving Automaton with Pickle Source: https://pyahocorasick.readthedocs.io/ Illustrates how to save and load an Aho-Corasick automaton using Python's standard `pickle` module. This method is convenient but can have high memory requirements. ```python import ahocorasick import pickle # build automaton A = ahocorasick.Automaton() # ... A.add_data, A.make_automaton # save current state with open(path, 'wb') as f: pickle.dump(A, f) # load saved state with open(path, 'rb') as f: B = pickle.load(f) ``` -------------------------------- ### keys/items/values([prefix, [wildcard, [how]]]) Source: https://pyahocorasick.readthedocs.io/ Iterators for keys, items, or values in the trie. ```APIDOC ## keys/items/values([prefix, [wildcard, [how]]]) ### Description Return an iterator on keys, items (key, value tuples), or values. Optional prefix matching and wildcard support provided. ``` -------------------------------- ### match(key) Source: https://pyahocorasick.readthedocs.io/ Checks if any prefix of the key exists in the trie. ```APIDOC ## match(key) ### Description Return True if there is a prefix (or key) equal to key present in the trie. ``` -------------------------------- ### Create and Use Automaton as Trie Source: https://pyahocorasick.readthedocs.io/ Initialize an Automaton and use it as a dictionary-like trie to add words and associated values. Check for word existence and retrieve values using dict-like methods. ```python >>> import ahocorasick >>> automaton = ahocorasick.Automaton() >>> for idx, key in enumerate('he her hers she'.split()): ... automaton.add_word(key, (idx, key)) ``` ```python >>> 'he' in automaton True >>> 'HER' in automaton False ``` ```python >>> automaton.get('he') (0, 'he') >>> automaton.get('she') (3, 'she') >>> automaton.get('cat', 'not exists') 'not exists' >>> automaton.get('dog') Traceback (most recent call last): File "", line 1, in KeyError ``` -------------------------------- ### Basic Trie Operations Source: https://pyahocorasick.readthedocs.io/ Demonstrates adding words to a trie, checking for existence, retrieving associated values, and removing words. Use for basic trie manipulation and verification. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> # add some key words to trie >>> for index, word in enumerate('he her hers she'.split()): ... A.add_word(word, (index, word)) >>> # test that these key words exists in the trie all right >>> 'he' in A True >>> 'HER' in A False >>> A.get('he') (0, 'he') >>> A.get('she') (3, 'she') >>> A.get('cat', '') '' >>> A.get('dog') Traceback (most recent call last): File "", line 1, in KeyError >>> A.remove_word('he') True >>> A.remove_word('he') False >>> A.pop('she') (3, 'she') >>> 'she' in A False ``` -------------------------------- ### Persistence and Statistics Source: https://pyahocorasick.readthedocs.io/ Methods for saving, loading, and retrieving statistics about the automaton. ```APIDOC ## save(path, serializer) ### Description Save content of automaton in an on-disc file. ### Parameters - **path** (str) - Required - File path. - **serializer** (callable) - Required - Callable to convert object to bytes. --- ## load(path, deserializer) ### Description Load automaton previously stored on disc. ### Parameters - **path** (str) - Required - File path. - **deserializer** (callable) - Required - Callable to convert bytes to object. --- ## get_stats() ### Description Return a dictionary containing Automaton statistics (nodes_count, words_count, longest_word, links_count, sizeof_node, total_size). ``` -------------------------------- ### len() Source: https://pyahocorasick.readthedocs.io/ Returns the number of keys in the trie. ```APIDOC ## len() ### Description Return the number of distinct keys added to the trie. ``` -------------------------------- ### Automaton Utility Methods Source: https://pyahocorasick.readthedocs.io/ Additional methods for inspecting the Automaton structure and statistics. ```APIDOC ## dump() ### Description Returns a three-tuple of lists describing the Automaton as a graph of (nodes, edges, failure links). ## get_stats() ### Description Returns a dictionary containing Automaton statistics. ## __sizeof__() ### Description Return the approximate size in bytes occupied by the Automaton instance. ``` -------------------------------- ### Automaton Trie Methods Source: https://pyahocorasick.readthedocs.io/ Methods for managing keys within the Automaton trie structure. ```APIDOC ## add_word(key, [value]) ### Description Add a key string to the trie and associate it with a value. ## remove_word(key) ### Description Remove a key string from the trie. ## pop(key) ### Description Remove a key string from the trie and return the associated value. ## exists(key) ### Description Return True if the key is present in the trie. ## match(key) ### Description Return True if there is a prefix or key equal to the provided key in the trie. ``` -------------------------------- ### Match Prefix or Key in Trie Source: https://pyahocorasick.readthedocs.io/ Checks if any prefix of the given key, including the key itself, exists in the trie. This differs from `exists()` which requires an exact match of the entire key. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("example", True) True A.match("e") True A.match("ex") True A.match("exa") True A.match("exam") True A.match("examp") True A.match("exampl") True A.match("example") True A.match("examples") False A.match("python") False ``` -------------------------------- ### Automaton Dictionary-like Methods Source: https://pyahocorasick.readthedocs.io/ Methods that allow the Automaton to behave like a Python dictionary. ```APIDOC ## get(key[, default]) ### Description Return the value associated with the key string. ## keys([prefix, [wildcard, [how]]]) ### Description Return an iterator on keys. ## values([prefix, [wildcard, [how]]]) ### Description Return an iterator on values associated with each key. ## items([prefix, [wildcard, [how]]]) ### Description Return an iterator on tuples of (key, value). ``` -------------------------------- ### exists(key) Source: https://pyahocorasick.readthedocs.io/ Checks if a key exists in the trie. ```APIDOC ## exists(key) ### Description Return True if the key is present in the trie. ### Parameters #### Path Parameters - **key** (string) - Required - The key to check for existence. ### Response - **boolean** - True if the key exists, False otherwise. ``` -------------------------------- ### Search Methods Source: https://pyahocorasick.readthedocs.io/ Methods for searching strings within the automaton, including standard, longest-match, and callback-based search. ```APIDOC ## iter(string, [start, [end]], ignore_white_space=False) ### Description Perform the Aho-Corasick search procedure using the provided input string. ### Parameters - **string** (str) - Required - The input string to search. - **start** (int) - Optional - Start index for string slice. - **end** (int) - Optional - End index for string slice. - **ignore_white_space** (bool) - Optional - Whether to ignore white spaces. ### Response - **iterator** (tuple) - Returns an iterator of (end_index, value) for found keys. --- ## iter_long(string, [start, [end]]) ### Description Perform the modified Aho-Corasick search procedure which matches only the longest words from the set. ### Parameters - **string** (str) - Required - The input string to search. - **start** (int) - Optional - Start index for string slice. - **end** (int) - Optional - End index for string slice. ### Response - **iterator** (tuple) - Returns an iterator of (end_index, value) for the longest found keys. --- ## find_all(string, callback, [start, [end]]) ### Description Perform the Aho-Corasick search and invoke a callback for each match. ### Parameters - **string** (str) - Required - The input string to search. - **callback** (callable) - Required - Function accepting (end_index, value). - **start** (int) - Optional - Start index. - **end** (int) - Optional - End index. ``` -------------------------------- ### Automaton Search Methods Source: https://pyahocorasick.readthedocs.io/ Methods for searching strings using the built automaton. ```APIDOC ## Automaton.iter(string, [start, [end]], ignore_white_space=False) ### Description Iterates over matches found in the provided string. ### Parameters - **string** (string) - Required - The string to search. - **start** (integer) - Optional - Start index. - **end** (integer) - Optional - End index. - **ignore_white_space** (boolean) - Optional - Whether to ignore whitespace. ## Automaton.find_all(string, callback, [start, [end]]) ### Description Finds all occurrences of words in the string and executes a callback for each match. ### Parameters - **string** (string) - Required - The string to search. - **callback** (function) - Required - Function to call on match. - **start** (integer) - Optional - Start index. - **end** (integer) - Optional - End index. ``` -------------------------------- ### Automaton Persistence Source: https://pyahocorasick.readthedocs.io/ Methods for saving and loading the state of an Automaton instance. ```APIDOC ## save(path, callable) ### Description Saves the current state of the automaton to a file. ### Parameters #### Query Parameters - **path** (string) - Required - File path to store data. - **callable** (function) - Optional - Required if store type is STORE_ANY; serializes python objects into bytes. ## load(path, callable) ### Description Loads an automaton state from a file. ### Parameters #### Query Parameters - **path** (string) - Required - File path containing saved data. - **callable** (function) - Required - Converts bytes back into python values. ``` -------------------------------- ### Iterate Over Keys in Trie Source: https://pyahocorasick.readthedocs.io/ Provides an iterator over the keys stored in the trie. Supports filtering by a prefix and using a wildcard character for pattern matching. Various matching modes (exact, at least, at most) can be specified. ```python keys([prefix, [wildcard, [how]]]) ``` -------------------------------- ### Add Word with Default Integer Value Source: https://pyahocorasick.readthedocs.io/ Shows adding words to an Automaton configured for integer values, where values default to their insertion order if not explicitly provided. Use this when you only need to track the presence and order of keys. ```python >>> import ahocorasick >>> B = ahocorasick.Automaton(ahocorasick.STORE_INTS) >>> B.add_word("cat") True >>> B.get() Traceback (most recent call last): File "", line 1, in IndexError: tuple index out of range >>> B.get("cat") 1 >>> B.add_word("dog") True >>> B.get("dog") 2 >>> B.add_word("tree", 42) True >>> B.get("tree") 42 >>> B.add_word("cat", 43) False >>> B.get("cat") 43 ``` -------------------------------- ### Check Key Existence in Trie Source: https://pyahocorasick.readthedocs.io/ Verifies if a key is present in the trie. This method is equivalent to using the 'in' keyword for membership testing. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("cat", 1) True A.exists("cat") True A.exists("dog") False 'elephant' in A False 'cat' in A True ``` -------------------------------- ### Automaton Class Methods Source: https://pyahocorasick.readthedocs.io/ Core methods for managing words and values within the Automaton structure. ```APIDOC ## Automaton.add_word(key, [value]) ### Description Adds a word to the automaton. Returns a boolean indicating success. ### Parameters - **key** (string) - Required - The word to add. - **value** (any) - Optional - The value associated with the key. ## Automaton.exists(key) ### Description Checks if a key exists in the automaton. ### Parameters - **key** (string) - Required - The key to check. ### Response - **boolean** - True if the key exists, False otherwise. ## Automaton.remove_word(word) ### Description Removes a word from the automaton. ### Parameters - **word** (string) - Required - The word to remove. ### Response - **boolean** - True if the word was removed, False otherwise. ``` -------------------------------- ### clear() Source: https://pyahocorasick.readthedocs.io/ Removes all keys from the trie. ```APIDOC ## clear() ### Description Remove all keys from the trie. This method invalidates all iterators. ``` -------------------------------- ### Add Word with Value Source: https://pyahocorasick.readthedocs.io/ Demonstrates adding a word to an Automaton with a required value. If the Automaton was created with `STORE_ANY` or `STORE_INTS` and no value is provided, it will raise a `ValueError` or default to an index, respectively. Use this when you need to associate specific data with each key. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> A.add_word("pyahocorasick") Traceback (most recent call last): File "", line 1, in ValueError: A value object is required as second argument. >>> A.add_word("pyahocorasick", (42, 'text')) True >>> A.get("pyhocorasick") (42, 'text') >>> A.add_word("pyahocorasick", 12) False >>> A.get("pyhocorasick") 12 ``` -------------------------------- ### Automaton Search Methods Source: https://pyahocorasick.readthedocs.io/ Methods for performing Aho-Corasick searches on strings, including standard iteration and longest-match iteration. ```APIDOC ## make_automaton() ### Description Finalize and create the Aho-Corasick automaton. ## iter(string, [start, [end]]) ### Description Perform the Aho-Corasick search procedure using the provided input string. ### Parameters #### Query Parameters - **string** (string) - Required - The input string to search. - **start** (int) - Optional - Start index. - **end** (int) - Optional - End index. ### Response - **iterator** (tuple) - Returns an iterator of tuples (end_index, value) for keys found in the string. ## iter_long(string, [start, [end]]) ### Description Returns an iterator that searches for longest, non-overlapping matches. ``` -------------------------------- ### Retrieve Value by Key from Trie Source: https://pyahocorasick.readthedocs.io/ Fetches the value associated with a given key. If the key is not found and no default is specified, a KeyError is raised. Otherwise, the default value is returned. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("cat", 42) True A.get("cat") 42 A.get("dog") Traceback (most recent call last): File "", line 1, in KeyError A.get("dog", "good dog") 'good dog' ``` -------------------------------- ### Iterate Over Key-Value Pairs in Trie Source: https://pyahocorasick.readthedocs.io/ Returns an iterator yielding tuples of (key, value) for entries in the trie. Filtering by prefix and wildcard matching are supported, similar to the `keys()` method. ```python items([prefix, [wildcard, [how]]]) ``` -------------------------------- ### Iterate Over Values in Trie Source: https://pyahocorasick.readthedocs.io/ Yields an iterator over the values stored in the trie. Key matching logic, including prefix and wildcard support, follows the same principles as the `keys()` method. ```python values([prefix, [wildcard, [how]]]) ``` -------------------------------- ### make_automaton() Source: https://pyahocorasick.readthedocs.io/ Finalizes the trie into an Aho-Corasick automaton. ```APIDOC ## make_automaton() ### Description Finalize and create the Aho-Corasick automaton based on the keys already added to the trie. ``` -------------------------------- ### Aho-Corasick Automaton Search Source: https://pyahocorasick.readthedocs.io/ Shows how to convert a trie into an Aho-Corasick automaton and then find all occurrences of stored keys within a given string. Useful for multi-pattern string searching. ```python >>> # convert the trie in an Aho-Corasick automaton >>> A = ahocorasick.Automaton() >>> for index, word in enumerate('he her hers she'.split()): ... A.add_word(word, (index, word)) >>> A.make_automaton() >>> # then find all occurrences of the stored keys in a string >>> for item in A.iter('_hershe_'): ... print(item) ... (2, (0, 'he')) (3, (1, 'her')) (4, (2, 'hers')) (6, (3, 'she')) (6, (0, 'he')) ``` -------------------------------- ### pop(word) Source: https://pyahocorasick.readthedocs.io/ Removes a word and returns its associated value. ```APIDOC ## pop(word) ### Description Remove given word from a trie and return associated values. Raise a KeyError if the word was not found. ``` -------------------------------- ### add_word Source: https://pyahocorasick.readthedocs.io/ Adds a key string to the trie and associates it with a value. Returns True if the word was inserted, False if it already existed. ```APIDOC ## add_word(key, [value]) ### Description Add a key string to the dict-like trie and associate this key with a value. The value requirement depends on the Automaton configuration. ### Parameters - **key** (string) - Required - The string key to add. - **value** (any) - Optional/Required - The value to associate with the key. Required for STORE_ANY, optional for STORE_INTS, forbidden for STORE_LENGTH. ### Response - **boolean** - True if the word was inserted, False if it already existed. ``` -------------------------------- ### longest_prefix(string) Source: https://pyahocorasick.readthedocs.io/ Finds the length of the longest prefix of a string that exists in the trie. ```APIDOC ## longest_prefix(string) ### Description Return the length of the longest prefix of string that exists in the trie. ### Parameters #### Path Parameters - **string** (string) - Required - The string to analyze. ``` -------------------------------- ### Convert Trie to Aho-Corasick Automaton and Search Source: https://pyahocorasick.readthedocs.io/ Convert the trie to an Aho-Corasick automaton using make_automaton(). Then, use the iter() method to find all occurrences of the added keys within a given text. The iter() method returns the end index and the associated value for each match. ```python >>> automaton.make_automaton() ``` ```python >>> for end_index, (insert_order, original_value) in automaton.iter(haystack): ... start_index = end_index - len(original_value) + 1 ... print((start_index, end_index, (insert_order, original_value))) ... assert haystack[start_index:start_index + len(original_value)] == original_value ... (1, 2, (0, 'he')) (1, 3, (1, 'her')) (1, 4, (2, 'hers')) (4, 6, (3, 'she')) (5, 6, (0, 'he')) ``` -------------------------------- ### Finalize Trie into Automaton Source: https://pyahocorasick.readthedocs.io/ Completes the trie construction and transforms it into an Aho-Corasick automaton. This operation is memory-efficient and sets the `Automaton.kind` attribute to `ahocorasick.AHOCORASICK` upon success. ```python make_automaton() ``` -------------------------------- ### Iterate All Matches with Aho-Corasick Source: https://pyahocorasick.readthedocs.io/ Use `iter` to find all occurrences of words in a string, including substrings that are part of longer matches. This method is suitable when all possible matches are required. ```python >>> list(A.iter(needle)) [(1, 'he'), (4, 'he'), (5, 'her'), (6, 'here'), (9, 'he'), (10, 'her')] ``` -------------------------------- ### Find Longest Prefix Length in Trie Source: https://pyahocorasick.readthedocs.io/ Determines the length of the longest prefix of a given string that exists within the trie. This is useful for prefix matching scenarios. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("he", True) True A.add_word("her", True) True A.add_word("hers", True) True A.longest_prefix("she") 0 A.longest_prefix("herself") 4 ``` -------------------------------- ### Pop Word and Value from Trie Source: https://pyahocorasick.readthedocs.io/ Removes a word from the trie and returns its associated value. If the word is not found, a KeyError is raised. This is useful for consuming items from the trie. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("cat", 1) True A.add_word("dog", 2) True A.pop("elephant") Traceback (most recent call last): File "", line 1, in KeyError A.pop("cat") 1 A.pop("dog") 2 A.pop("cat") Traceback (most recent call last): File "", line 1, in KeyError ``` -------------------------------- ### Iterate Longest Matches with Aho-Corasick Source: https://pyahocorasick.readthedocs.io/ Use `iter_long` to find only the longest matches in a string, preventing substrings of other matches from being reported. This is useful when you need to prioritize longer word occurrences. ```python >>> import ahocorasick >>> A = ahocorasick.Automaton() >>> A.add_word("he", "he") True >>> A.add_word("her", "her") True >>> A.add_word("here", "here") True >>> A.make_automaton() >>> needle = "he here her" >>> list(A.iter_long(needle)) [(1, 'he'), (6, 'here'), (10, 'her')] ``` -------------------------------- ### Clear All Keys from Trie Source: https://pyahocorasick.readthedocs.io/ Removes all keys and their associated values from the trie, effectively resetting it to an empty state. This operation invalidates any existing iterators. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("cat", 1) True A.add_word("dog", 2) True A.add_word("elephant", 3) True len(A) 3 A.clear() len(A) 0 ``` -------------------------------- ### remove_word(word) Source: https://pyahocorasick.readthedocs.io/ Removes a word from the trie. ```APIDOC ## remove_word(word) ### Description Remove given word from a trie. Return True if word was found, False otherwise. ``` -------------------------------- ### Remove Word from Trie Source: https://pyahocorasick.readthedocs.io/ Removes a specified word from the trie. Returns True if the word was found and removed, False otherwise. Repeated calls for a non-existent word will return False. ```python import ahocorasick A = ahocorasick.Automaton() A.add_word("cat", 1) True A.add_word("dog", 2) True A.remove_word("cat") True A.remove_word("cat") False A.remove_word("dog") True A.remove_word("dog") False ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.