From 61fbed281ec23f6b127185be3f97a9b689b531df Mon Sep 17 00:00:00 2001 From: Lon Hohberger Date: Thu, 14 Dec 2023 10:23:36 -0500 Subject: [PATCH] nym: Expand usability This expands the number of translations and enables the caller to (optionally) override the default translations. --- tests/test_strutil_nym.py | 27 +++++++++++++++++++++++++++ toolchest/strutil.py | 13 +++++++++---- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/tests/test_strutil_nym.py b/tests/test_strutil_nym.py index 9df0090..e50d772 100644 --- a/tests/test_strutil_nym.py +++ b/tests/test_strutil_nym.py @@ -7,6 +7,8 @@ def test_identity(): assert nym('abc') == 'abc' + assert nym('') == '' + assert nym(None) is None def test_spaces(): @@ -19,3 +21,28 @@ def test_tabs(): def test_lowercase(): assert nym('aBcDeF') == 'abcdef' + + +def test_underscores(): + assert nym('a.b') == 'a_b' + assert nym('a-b+c') == 'a_b_c' + + +def test_removes(): + assert nym('a(b)[c]{d}/e=f') == 'abcdef' + + +def test_non_null(): + # If we pass in a string, we should get _something_ back, + # even if all characters would otherwise be removed + assert nym('()') + + +def test_integer(): + assert nym(1) == '1' + + +def test_params(): + assert nym('1', remove='1') == '_' + assert nym('12', underscore='1') == '_2' + assert nym('123', underscore='1', remove='3') == '_2' diff --git a/toolchest/strutil.py b/toolchest/strutil.py index 62c2de6..861ded7 100644 --- a/toolchest/strutil.py +++ b/toolchest/strutil.py @@ -32,7 +32,7 @@ def regex_match(pattern, arg): return False -def nym(arg): +def nym(arg, underscore='+-. !?;:\'",\t', remove='()[]{}?<>/='): ''' This is for allowing case and quote flexibility for strings when searching dictionaries or other data sets based on user input (esp. @@ -44,10 +44,15 @@ def nym(arg): Parameters: arg (string): A string to create the nym for + underscore (string): A set of characters to replace with underscores + remove (string): A set of characters to remove from the return value Returns: - ret (string): A lower-case string with whitespace swapped to _ + ret (string): A lower-case string with characters translated + or removed. ''' - ret = arg.lower().replace(' ', '_') - ret = ret.replace('\t', '_') + if (ret := arg) not in ('', None): + tr = str.maketrans(underscore, '_' * len(underscore), remove) + ret = str(arg).lower().translate(tr) or '_' + return ret