1
0
Fork 0
This repository has been archived on 2023-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
dailyreleases/dailyreleases/util.py

47 lines
1.6 KiB
Python
Raw Normal View History

import difflib
2019-03-08 02:07:22 +01:00
from typing import Sequence, List
2019-03-08 02:07:22 +01:00
def humanize(n: int, precision=2, prefix="bin", suffix="B") -> str:
"""
Return a humanized string representation of a number (of bytes).
Adapted from Doug Latornell - http://code.activestate.com/recipes/577081/
"""
abbrevs = {
"dec": [
(1000 ** 5, 'P' + suffix),
(1000 ** 4, 'T' + suffix),
(1000 ** 3, 'G' + suffix),
(1000 ** 2, 'M' + suffix),
(1000 ** 1, 'k' + suffix)
],
"bin": [
(1 << 50, 'Pi' + suffix),
(1 << 40, 'Ti' + suffix),
(1 << 30, 'Gi' + suffix),
(1 << 20, 'Mi' + suffix),
(1 << 10, 'ki' + suffix)
]
}
factor, suffix = next(((f, s) for f, s in abbrevs[prefix] if n >= f), (1, suffix))
return "{1:.{0}f}".format(precision, n / factor).rstrip("0").rstrip(".") + suffix
2019-03-08 02:07:22 +01:00
def case_insensitive_close_matches(word: str, possibilities: Sequence[str], n=3, cutoff=0.6) -> List[str]:
"""
Python's difflib.get_close_matches does case sensitive sequence matching, this function decorates the library
function to make it case insensitive.
"""
possibilities = {sequence.lower(): sequence for sequence in possibilities}
close_matches = difflib.get_close_matches(word.lower(), possibilities, n=n, cutoff=cutoff)
return [possibilities[m] for m in close_matches]
2019-03-08 02:07:22 +01:00
def markdown_escape(text: str) -> str:
"""
Escape markdown.
"""
special = ("\\", "`", "*", "_", "{", "}", "[", "]", "(", ")", "#", "+", "-", ".", "!", "|")
table = {s: f"\\{s}" for s in special}
return text.translate(str.maketrans(table))