| 1 |
from copy import deepcopy |
| 2 |
|
| 3 |
from lunr.token import Token |
| 4 |
from lunr.utils import as_string |
| 5 |
|
| 6 |
SEPARATOR_CHARS = " \t\n\r\f\v\xa0-" |
| 7 |
|
| 8 |
|
| 9 |
def default_separator(char): |
| 10 |
return char and char in SEPARATOR_CHARS |
| 11 |
|
| 12 |
|
| 13 |
def Tokenizer(obj, metadata=None, separator=None): |
| 14 |
"""Splits a string into tokens ready to be inserted into the search index. |
| 15 |
|
| 16 |
Args: |
| 17 |
metadata (dict): Optional metadata can be passed to the tokenizer, this |
| 18 |
metadata will be cloned and added as metadata to every token that is |
| 19 |
created from the object to be tokenized. |
| 20 |
separator (callable or compiled regex): This tokenizer will convert its |
| 21 |
parameter to a string by calling `str` and then will split this |
| 22 |
string on characters for which `separator` is True. Lists will have |
| 23 |
their elements converted to strings and wrapped in a lunr `Token`. |
| 24 |
|
| 25 |
Returns: |
| 26 |
List of Token instances. |
| 27 |
""" |
| 28 |
if obj is None: |
| 29 |
return [] |
| 30 |
|
| 31 |
metadata = metadata or {} |
| 32 |
|
| 33 |
if isinstance(obj, (list, tuple)): |
| 34 |
return [ |
| 35 |
Token(as_string(element).lower(), deepcopy(metadata)) for element in obj |
| 36 |
] |
| 37 |
|
| 38 |
if separator is None: |
| 39 |
is_separator = default_separator |
| 40 |
elif callable(separator): |
| 41 |
is_separator = separator |
| 42 |
else: # must be a regex, remove when dropping support for 2.7 |
| 43 |
is_separator = lambda c: separator.match(c) # noqa |
| 44 |
|
| 45 |
string = str(obj).lower() |
| 46 |
length = len(string) |
| 47 |
tokens = [] |
| 48 |
slice_start = 0 |
| 49 |
for slice_end in range(length + 1): |
| 50 |
char = string[slice_end] if slice_end != length else "" |
| 51 |
slice_length = slice_end - slice_start |
| 52 |
if is_separator(char) or slice_end == length: |
| 53 |
if slice_length > 0: |
| 54 |
token_metadata = {} |
| 55 |
token_metadata["position"] = [slice_start, slice_length] |
| 56 |
token_metadata["index"] = len(tokens) |
| 57 |
token_metadata.update(metadata) |
| 58 |
|
| 59 |
sl = slice(slice_start, slice_end) |
| 60 |
tokens.append(Token(string[sl], token_metadata)) |
| 61 |
|
| 62 |
slice_start = slice_end + 1 |
| 63 |
|
| 64 |
return tokens |