-
Notifications
You must be signed in to change notification settings - Fork 1
/
text.py
50 lines (35 loc) · 1.5 KB
/
text.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import re
def _comma_and_helper(*values, period, and_or_or):
period = '.' if period else ''
len_values = len(values)
if len_values == 0:
return ""
elif len_values == 1:
return f"{values[0]}{period}"
else:
return f"{', '.join(values[:-1])} {and_or_or} {values[-1]}{period}"
def comma_and_and(*values, period=True):
""" Return a properly formatted string, eg: a, b and c. """
return _comma_and_helper(*values, period=period, and_or_or="and")
def comma_and_or(*values, period=True):
""" Return a properly formatted string, eg: a, b or c. """
return _comma_and_helper(*values, period=period, and_or_or="or")
def plur_sing(count, word, suffix=None):
""" Conditionally add an 's' for example, if count isn't 1. """
if suffix is None:
suffix = "s"
return f"{count} {word}{suffix * (count != 1)}"
def _pattern(pattern):
return re.escape(str(pattern))
def replace(string, reverse=False, **translation):
""" Replace strings in a string with other strings!
Uses regex and * is treated as wildcard. """
for a, b in translation.items():
if reverse:
a, b = b, a
string = re.sub(_pattern(a), str(b).replace("\\", "\\\\"), string)
return string
def match(string, *patterns):
""" Search string for matches, True if any match is found.
Uses regex and * is treated as wildcard. """
return any(re.search(replace(_pattern(pattern), **{r"\*": ".+"}), string, re.IGNORECASE) for pattern in patterns)