trieregex
trieregex creates efficient regular expressions (regexes) by storing a list of words in a trie structure, and translating the trie into a more compact pattern.
The speed performance of a trie-based regex (e.g. r'(?:under(?:sta(?:nd|te))|take|go)?)'
), compared to a flat regex union (i.e., r'(?:understand|understate|undertake|undergo)'
, becomes obvious when using extremely large word lists, and especially when more specific or complicated contexts are specified at the boundaries. The processing time of using this package itself is also minimized with memoization.
Installation
pip install trieregex
Usage
import re
from trieregex import TrieRegEx as TRE
words = ['lemon', 'lime', 'pomelo', 'orange', 'citron']
more_words = ['grapefruit', 'grape', 'tangerine', 'tangelo']
tre = TRE()
tre = TRE(*words)
tre.add('kumquat')
tre.add(*more_words)
tre.remove('citron')
tre.remove(*words)
tre.has('citron')
tre.has('tangerine')
tre.regex()
pattern = re.compile(f'\\b{tre.regex()}\\b')
pattern
pattern.findall("A kumquat is tastier than a loquat")
tre.initials()
tre.finals()
The last two methods are intended for the user to check what boundary contexts may be appropriate to set in the final regex. More discussed below.
Boundaries
trieregex does not include any default boundaries (such as r'\b'
) in the pattern returned from its TrieRegEx.regex()
method, so that the user can determine what is appropriate for their particular use case.
Consider a fictitious brand name !Citrus
with an exclamation mark at the beginning, using r'\b'
to define its boundaries in an attempt to catch it:
string = 'I love !Citrus products!'
re.findall(r'\b(!Citrus)\b', string)
The re.findall()
call returns an empty list because the first r'\b'
is not matched. While r'\b'
stands for the boundary between a word character and a non-word character, the exclamation mark and its preceding space character are both non-word characters.
An appropriate regex for catching '!Citrus'
can be written as follows, where the context before the exclamation mark is either start-of-string (r'^'
) or a non-word character (r'[^\w]'
):
re.findall(r'(?:^|[^\w])(!Citrus)\b', string)
This package was designed to allow any pattern in its trie, not just normal words bound by space and punctuation, so that the user can define their own regex context, and have the option to avoid data normalization when it is undesirable.
Python version comptability
Due to f-strings and type hints, this package is only comptible with Python versions >=3.6.
For Python versions >=2.7, <3.6, backports such as future-fstrings
and typing
are available.