From 50df7bd9f30f0b7a630c0248b5ebb1bc36c6f271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pac=C3=B4me?= Date: Mon, 22 Feb 2021 13:02:24 +0100 Subject: [PATCH] added acronyms capitalization to humanize function acronyms can be added using the add_acronym function humanize will then capitalize all the added acronyms example: >>> humanize('get_http_url') 'Get http url' >>> add_acronym(['http', 'url']) >>> humanize('get_http_url') 'Get HTTP URL' --- inflection/__init__.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/inflection/__init__.py b/inflection/__init__.py index c18a0b6..ddc07e4 100644 --- a/inflection/__init__.py +++ b/inflection/__init__.py @@ -11,6 +11,7 @@ """ import re import unicodedata +from typing import Union __version__ = '0.5.1' @@ -88,6 +89,26 @@ 'species'} +ACRONYMS = set() +__acronyms_regex = re.compile(r'a^') # initial regex matches nothing + + +def add_acronym(acronym: Union[str, list[str]]) -> None: + """ + Add an acronym to be capitalized by :func:`humanize` + + :param acronym: a single string or a list of strings representing the acronyms to add (case is ignored) + """ + global ACRONYMS, __acronyms_regex + if type(acronym) is str: + acronym = acronym.lower() + elif type(acronym) is list: + acronym = map(lambda s: s.lower(), acronym) + ACRONYMS.update(acronym) + pattern = '(' + '|'.join(ACRONYMS) + ')' + __acronyms_regex = re.compile(pattern, re.IGNORECASE) + + def _irregular(singular: str, plural: str) -> None: """ A convenience function to add appropriate rules to plurals and singular @@ -198,6 +219,7 @@ def humanize(word: str) -> str: word = word.replace('_', ' ') word = re.sub(r"(?i)([a-z\d]*)", lambda m: m.group(1).lower(), word) word = re.sub(r"^\w", lambda m: m.group(0).upper(), word) + word = __acronyms_regex.sub(lambda m: m.group(0).upper(), word) return word