diff options
| author | Val Neekman <un33kvu@gmail.com> | 2019-01-03 18:03:36 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-01-03 18:03:36 -0500 |
| commit | 1340320455f7201117ac3970c0facf5d1e0f8767 (patch) | |
| tree | 72f41588ccc9ae7281220f12fba1f6aff2d5801f /slugify/slugify.py | |
| parent | 683364ea0f4637364b84486ef24124ece0e0597c (diff) | |
| download | python-slugify-2.0.1.tar.gz | |
Add replacements option (#67)2.0.1
Diffstat (limited to 'slugify/slugify.py')
| -rw-r--r-- | slugify/slugify.py | 14 |
1 files changed, 13 insertions, 1 deletions
diff --git a/slugify/slugify.py b/slugify/slugify.py index ccd33a8..59e9672 100644 --- a/slugify/slugify.py +++ b/slugify/slugify.py @@ -75,7 +75,8 @@ def smart_truncate(string, max_length=0, word_boundary=False, separator=' ', sav def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, - separator=DEFAULT_SEPARATOR, save_order=False, stopwords=(), regex_pattern=None, lowercase=True): + separator=DEFAULT_SEPARATOR, save_order=False, stopwords=(), regex_pattern=None, lowercase=True, + replacements=()): """ Make a slug from the given text. :param text (str): initial text @@ -89,9 +90,15 @@ def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, w :param stopwords (iterable): words to discount :param regex_pattern (str): regex pattern for allowed characters :param lowercase (bool): activate case sensitivity by setting it to False + :param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']] :return (str): """ + # user-specific replacements + if replacements: + for old, new in replacements: + text = text.replace(old, new) + # ensure text is unicode if not isinstance(text, _unicode_type): text = _unicode(text, 'utf-8', 'ignore') @@ -158,6 +165,11 @@ def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, w words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords] text = DEFAULT_SEPARATOR.join(words) + # finalize user-specific replacements + if replacements: + for old, new in replacements: + text = text.replace(old, new) + # smart truncate if requested if max_length > 0: text = smart_truncate(text, max_length, word_boundary, DEFAULT_SEPARATOR, save_order) |
