| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2015-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Collection of functions that work on strings/text""" |
| 10 |
|
| 11 |
import html |
| 12 |
import urllib.parse |
| 13 |
import re as re_module |
| 14 |
|
| 15 |
try: |
| 16 |
re_compile = re_module._compiler.compile |
| 17 |
except AttributeError: |
| 18 |
re_compile = re_module.sre_compile.compile |
| 19 |
|
| 20 |
HTML_RE = re_compile(r"<[^>]+>") |
| 21 |
PATTERN_CACHE = {} |
| 22 |
|
| 23 |
|
| 24 |
def re(pattern): |
| 25 |
"""Compile a regular expression pattern""" |
| 26 |
try: |
| 27 |
return PATTERN_CACHE[pattern] |
| 28 |
except KeyError: |
| 29 |
p = PATTERN_CACHE[pattern] = re_compile(pattern) |
| 30 |
return p |
| 31 |
|
| 32 |
|
| 33 |
def remove_html(txt, repl=" ", sep=" "): |
| 34 |
"""Remove html-tags from a string""" |
| 35 |
try: |
| 36 |
txt = HTML_RE.sub(repl, txt) |
| 37 |
except TypeError: |
| 38 |
return "" |
| 39 |
if sep: |
| 40 |
return sep.join(txt.split()) |
| 41 |
return txt.strip() |
| 42 |
|
| 43 |
|
| 44 |
def split_html(txt): |
| 45 |
"""Split input string by HTML tags""" |
| 46 |
try: |
| 47 |
return [ |
| 48 |
unescape(x).strip() |
| 49 |
for x in HTML_RE.split(txt) |
| 50 |
if x and not x.isspace() |
| 51 |
] |
| 52 |
except TypeError: |
| 53 |
return [] |
| 54 |
|
| 55 |
|
| 56 |
def slugify(value): |
| 57 |
"""Convert a string to a URL slug |
| 58 |
|
| 59 |
Adapted from: |
| 60 |
https://github.com/django/django/blob/master/django/utils/text.py |
| 61 |
""" |
| 62 |
value = re(r"[^\w\s-]").sub("", str(value).lower()) |
| 63 |
return re(r"[-\s]+").sub("-", value).strip("-_") |
| 64 |
|
| 65 |
|
| 66 |
def sanitize_whitespace(value): |
| 67 |
"""Replace all whitespace characters with a single space""" |
| 68 |
return re(r"\s+").sub(" ", value.strip()) |
| 69 |
|
| 70 |
|
| 71 |
def ensure_http_scheme(url, scheme="https://"): |
| 72 |
"""Prepend 'scheme' to 'url' if it doesn't have one""" |
| 73 |
if url and not url.startswith(("https://", "http://")): |
| 74 |
return scheme + url.lstrip("/:") |
| 75 |
return url |
| 76 |
|
| 77 |
|
| 78 |
def root_from_url(url, scheme="https://"): |
| 79 |
"""Extract scheme and domain from a URL""" |
| 80 |
if not url.startswith(("https://", "http://")): |
| 81 |
try: |
| 82 |
return scheme + url[:url.index("/")] |
| 83 |
except ValueError: |
| 84 |
return scheme + url |
| 85 |
try: |
| 86 |
return url[:url.index("/", 8)] |
| 87 |
except ValueError: |
| 88 |
return url |
| 89 |
|
| 90 |
|
| 91 |
def filename_from_url(url): |
| 92 |
"""Extract the last part of an URL to use as a filename""" |
| 93 |
try: |
| 94 |
return url.partition("?")[0].rpartition("/")[2] |
| 95 |
except Exception: |
| 96 |
return "" |
| 97 |
|
| 98 |
|
| 99 |
def ext_from_url(url): |
| 100 |
"""Extract the filename extension of an URL""" |
| 101 |
name, _, ext = filename_from_url(url).rpartition(".") |
| 102 |
return ext.lower() if name else "" |
| 103 |
|
| 104 |
|
| 105 |
def nameext_from_url(url, data=None): |
| 106 |
"""Extract the last part of an URL and fill 'data' accordingly""" |
| 107 |
if data is None: |
| 108 |
data = {} |
| 109 |
|
| 110 |
filename = unquote(filename_from_url(url)) |
| 111 |
name, _, ext = filename.rpartition(".") |
| 112 |
if name and len(ext) <= 16: |
| 113 |
data["filename"] = name |
| 114 |
data["extension"] = ext.lower() |
| 115 |
else: |
| 116 |
data["filename"] = filename |
| 117 |
data["extension"] = "" |
| 118 |
|
| 119 |
return data |
| 120 |
|
| 121 |
|
| 122 |
def nameext_from_name(filename, data=None): |
| 123 |
"""Extract the last part of a file name and fill 'data' accordingly""" |
| 124 |
if data is None: |
| 125 |
data = {} |
| 126 |
|
| 127 |
name, _, ext = filename.rpartition(".") |
| 128 |
if name and len(ext) <= 16: |
| 129 |
data["filename"] = name |
| 130 |
data["extension"] = ext.lower() |
| 131 |
else: |
| 132 |
data["filename"] = filename |
| 133 |
data["extension"] = "" |
| 134 |
|
| 135 |
return data |
| 136 |
|
| 137 |
|
| 138 |
def filename_from_contentdisposition(cd): |
| 139 |
if (pos := cd.find("filename*=")) >= 0: |
| 140 |
pos += 10 |
| 141 |
if cd[pos] == '"': |
| 142 |
pos += 1 |
| 143 |
value = cd[pos:cd.find('"', pos)] |
| 144 |
else: |
| 145 |
end = cd.find(";", pos) |
| 146 |
value = cd[pos:None if end < 0 else end] |
| 147 |
try: |
| 148 |
charset, _, value = value.split("'", 2) |
| 149 |
return unquote(value, charset, "replace") |
| 150 |
except Exception: |
| 151 |
pass |
| 152 |
|
| 153 |
if (pos := cd.find("filename=")) >= 0: |
| 154 |
pos += 9 |
| 155 |
if cd[pos] == '"': |
| 156 |
pos += 1 |
| 157 |
value = cd[pos:cd.find('"', pos)] |
| 158 |
else: |
| 159 |
end = cd.find(";", pos) |
| 160 |
value = cd[pos:None if end < 0 else end] |
| 161 |
return value |
| 162 |
|
| 163 |
return "" |
| 164 |
|
| 165 |
|
| 166 |
def extract(txt, begin, end, pos=None): |
| 167 |
"""Extract the text between 'begin' and 'end' from 'txt' |
| 168 |
|
| 169 |
Args: |
| 170 |
txt: String to search in |
| 171 |
begin: First string to be searched for |
| 172 |
end: Second string to be searched for after 'begin' |
| 173 |
pos: Starting position for searches in 'txt' |
| 174 |
|
| 175 |
Returns: |
| 176 |
The string between the two search-strings 'begin' and 'end' beginning |
| 177 |
with position 'pos' in 'txt' as well as the position after 'end'. |
| 178 |
|
| 179 |
If at least one of 'begin' or 'end' is not found, None and the original |
| 180 |
value of 'pos' is returned |
| 181 |
|
| 182 |
Examples: |
| 183 |
extract("abcde", "b", "d") -> "c" , 4 |
| 184 |
extract("abcde", "b", "d", 3) -> None, 3 |
| 185 |
""" |
| 186 |
try: |
| 187 |
first = txt.index(begin, pos) + len(begin) |
| 188 |
last = txt.index(end, first) |
| 189 |
return txt[first:last], last+len(end) |
| 190 |
except Exception: |
| 191 |
return None, 0 if pos is None else pos |
| 192 |
|
| 193 |
|
| 194 |
def extr(txt, begin, end, default=""): |
| 195 |
"""Stripped-down version of 'extract()'""" |
| 196 |
try: |
| 197 |
first = txt.index(begin) + len(begin) |
| 198 |
return txt[first:txt.index(end, first)] |
| 199 |
except Exception: |
| 200 |
return default |
| 201 |
|
| 202 |
|
| 203 |
def rextract(txt, begin, end, pos=None): |
| 204 |
try: |
| 205 |
lbeg = len(begin) |
| 206 |
first = txt.rindex(begin, None, pos) |
| 207 |
last = txt.index(end, first + lbeg) |
| 208 |
return txt[first + lbeg:last], first |
| 209 |
except Exception: |
| 210 |
return None, -1 if pos is None else pos |
| 211 |
|
| 212 |
|
| 213 |
def rextr(txt, begin, end, pos=None, default=""): |
| 214 |
"""Stripped-down version of 'rextract()'""" |
| 215 |
try: |
| 216 |
first = txt.rindex(begin, None, pos) + len(begin) |
| 217 |
return txt[first:txt.index(end, first)] |
| 218 |
except Exception: |
| 219 |
return default |
| 220 |
|
| 221 |
|
| 222 |
def iextr(txt, needle, begin, end, pos=None, default=""): |
| 223 |
"""Extract text between 'begin' and 'end' from the position of 'needle'""" |
| 224 |
try: |
| 225 |
pos = txt.index(needle, pos) |
| 226 |
return txt[txt.rindex(begin, None, pos)+len(begin): |
| 227 |
txt.index(end, pos+len(needle))] |
| 228 |
except Exception: |
| 229 |
return default |
| 230 |
|
| 231 |
|
| 232 |
def extract_all(txt, rules, pos=None, values=None): |
| 233 |
"""Calls extract for each rule and returns the result in a dict""" |
| 234 |
if values is None: |
| 235 |
values = {} |
| 236 |
for key, begin, end in rules: |
| 237 |
result, pos = extract(txt, begin, end, pos) |
| 238 |
if key: |
| 239 |
values[key] = result |
| 240 |
return values, 0 if pos is None else pos |
| 241 |
|
| 242 |
|
| 243 |
def extract_iter(txt, begin, end, pos=None): |
| 244 |
"""Yield values that would be returned by repeated calls of extract()""" |
| 245 |
try: |
| 246 |
index = txt.index |
| 247 |
lbeg = len(begin) |
| 248 |
lend = len(end) |
| 249 |
while True: |
| 250 |
first = index(begin, pos) + lbeg |
| 251 |
last = index(end, first) |
| 252 |
pos = last + lend |
| 253 |
yield txt[first:last] |
| 254 |
except Exception: |
| 255 |
return |
| 256 |
|
| 257 |
|
| 258 |
def extract_from(txt, pos=None, default=""): |
| 259 |
"""Returns a function object that extracts from 'txt'""" |
| 260 |
def extr(begin, end, index=txt.index, txt=txt): |
| 261 |
nonlocal pos |
| 262 |
try: |
| 263 |
first = index(begin, pos) + len(begin) |
| 264 |
last = index(end, first) |
| 265 |
pos = last + len(end) |
| 266 |
return txt[first:last] |
| 267 |
except Exception: |
| 268 |
return default |
| 269 |
return extr |
| 270 |
|
| 271 |
|
| 272 |
extract_urls = re(r"https?://[^\s\"'<>\\]+").findall |
| 273 |
|
| 274 |
|
| 275 |
def parse_hex_escapes(txt): |
| 276 |
"""Convert hex escapes in 'txt' into actual characters""" |
| 277 |
return re(r"\\x([0-9a-fA-F]{2})").sub(_hex_to_char, txt) |
| 278 |
|
| 279 |
|
| 280 |
def parse_unicode_escapes(txt): |
| 281 |
"""Convert JSON Unicode escapes in 'txt' into actual characters""" |
| 282 |
if "\\u" in txt: |
| 283 |
return re(r"\\u([0-9a-fA-F]{4})").sub(_hex_to_char, txt) |
| 284 |
return txt |
| 285 |
|
| 286 |
|
| 287 |
def _hex_to_char(match): |
| 288 |
return chr(int(match[1], 16)) |
| 289 |
|
| 290 |
|
| 291 |
def parse_bytes(value, default=0, suffixes="bkmgtp"): |
| 292 |
"""Convert a bytes-amount ("500k", "2.5M", ...) to int""" |
| 293 |
if not value: |
| 294 |
return default |
| 295 |
|
| 296 |
value = str(value).strip() |
| 297 |
last = value[-1].lower() |
| 298 |
|
| 299 |
if last in suffixes: |
| 300 |
mul = 1024 ** suffixes.index(last) |
| 301 |
value = value[:-1] |
| 302 |
else: |
| 303 |
mul = 1 |
| 304 |
|
| 305 |
try: |
| 306 |
return round(float(value) * mul) |
| 307 |
except ValueError: |
| 308 |
return default |
| 309 |
|
| 310 |
|
| 311 |
def parse_int(value, default=0): |
| 312 |
"""Convert 'value' to int""" |
| 313 |
if not value: |
| 314 |
return default |
| 315 |
try: |
| 316 |
return int(value) |
| 317 |
except Exception: |
| 318 |
return default |
| 319 |
|
| 320 |
|
| 321 |
def parse_float(value, default=0.0): |
| 322 |
"""Convert 'value' to float""" |
| 323 |
if not value: |
| 324 |
return default |
| 325 |
try: |
| 326 |
return float(value) |
| 327 |
except Exception: |
| 328 |
return default |
| 329 |
|
| 330 |
|
| 331 |
def parse_query(qs, empty=False): |
| 332 |
"""Parse a query string into name-value pairs |
| 333 |
|
| 334 |
Ignore values whose name has been seen before |
| 335 |
""" |
| 336 |
if not qs: |
| 337 |
return {} |
| 338 |
|
| 339 |
result = {} |
| 340 |
try: |
| 341 |
for name_value in qs.split("&"): |
| 342 |
name, eq, value = name_value.partition("=") |
| 343 |
if eq or empty: |
| 344 |
name = unquote(name.replace("+", " ")) |
| 345 |
if name not in result: |
| 346 |
result[name] = unquote(value.replace("+", " ")) |
| 347 |
except Exception: |
| 348 |
pass |
| 349 |
return result |
| 350 |
|
| 351 |
|
| 352 |
def parse_query_list(qs, as_list=()): |
| 353 |
"""Parse a query string into name-value pairs |
| 354 |
|
| 355 |
Combine values of names in 'as_list' into lists |
| 356 |
""" |
| 357 |
if not qs: |
| 358 |
return {} |
| 359 |
|
| 360 |
result = {} |
| 361 |
try: |
| 362 |
for name_value in qs.split("&"): |
| 363 |
name, eq, value = name_value.partition("=") |
| 364 |
if eq: |
| 365 |
name = unquote(name.replace("+", " ")) |
| 366 |
value = unquote(value.replace("+", " ")) |
| 367 |
if name in as_list: |
| 368 |
if name in result: |
| 369 |
result[name].append(value) |
| 370 |
else: |
| 371 |
result[name] = [value] |
| 372 |
elif name not in result: |
| 373 |
result[name] = value |
| 374 |
except Exception: |
| 375 |
pass |
| 376 |
return result |
| 377 |
|
| 378 |
|
| 379 |
def build_query(params): |
| 380 |
return "&".join([ |
| 381 |
(f"{quote(name)}=" |
| 382 |
f"{quote(str(value) if isinstance(value, int) else value)}") |
| 383 |
for name, value in params.items() |
| 384 |
]) |
| 385 |
|
| 386 |
|
| 387 |
urljoin = urllib.parse.urljoin |
| 388 |
|
| 389 |
quote = urllib.parse.quote |
| 390 |
unquote = urllib.parse.unquote |
| 391 |
|
| 392 |
escape = html.escape |
| 393 |
unescape = html.unescape |