Text formatting¶
This package contains functions and classes to format a text or a message.
Generic formatters¶
-
py314.formats.core.wraps(text, *wrappers)¶ Recursively wrap text inside *wrappers.
-
py314.formats.core.format_specification(width, *wrappers, mode='', prefix='', suffix='', inner_prefix='', inner_suffix='')¶ The formatted string is of the form
${prefix}${value}${suffix}, where the placeholders ${prefix} and ${suffix} are given by the associated keyword arguments and ${value} is given as below.fmt = ''.join(['%', mode, str(width), 's']) value = wraps(''.join([inner_prefix, fmt, inner_suffix]), *wrappers)
Parameters: - width (int) – The style width.
- *wrappers – String wrappers.
- mode (str [optional]) – The alignment mode.
- prefix (str [optional]) – A prefix string.
- suffix (str [optional]) – A suffix string.
- inner_prefix (str [optional]) – An inner prefix string.
- inner_suffix (str [optional]) – An inner suffix string.
-
class
py314.formats.core.Styler(formatter=None, *args, **kwargs)¶ Basic formatter whose constructor is overloaded as follows. If a single argument is given, it is either a %-string format or a callable. In the first case, the formatter is defined to be the call to the %-operator.
If two or more arguments are provided, the formatter is a partial function constructed with the given parameters and via functools.partial.
-
feed(*args, **kwargs)¶ Delegate the formatting to the internal formatter. On exception, the default formatter is used instead.
-
classmethod
join_all(*args, **kwargs)¶ Default formatter joining all positional arguments and keys.
-
-
class
py314.formats.core.Format(*args, mode='', suffix='')¶ Positional arguments are common wrappers and initial pushables entities. Wrappers are
strand must be given first; the rest is considered as pushable entities and every one of them is pushed viapush(), and therefore, positional arguments arestrorint.Parameters: -
push(slot, *wrappers, prefix='', suffix='')¶ Add a slot string to the slots.
Parameters:
-
push_wrapped(width, *wrappers)¶ Push slots given by
format_specification(), where the wrappers are extended with the wrappers given at construction and the mode and the inner_prefix parameters are those given at the construction.Parameters: - width (int) – A width.
- *wrappers – A list of strings wrapping the format specification.
-
clear()¶ Clear the current format stack.
-
Codeblock and styles¶
-
class
py314.formats.codeblock.Style¶ Rich code-blocks text style enumeration.
-
AsciiDoc¶
-
AHK¶
-
Bash¶
-
Diff¶
-
DSConfig¶
-
Markdown¶
-
Python¶
-
PHP¶
-
CSS¶
-
HTML¶
-
YML¶
-
LDIF¶
-
-
py314.formats.codeblock.codeblock(text, style=None, *, endl=False)¶ Convert text to a specific codeblock style.
Parameters:
-
py314.formats.codeblock.markdown(text, *, endl=False)¶ Partialization of
codeblock()with a markdown style.
Characters and strings¶
Insertion¶
-
py314.formats.text.multichar(char, n=1)¶ Return n times the char.
-
py314.formats.text.newline(n=1)¶ Return n endlines.
-
py314.formats.text.spaces(n=1)¶ Return n spaces.
Conditional¶
-
py314.formats.text.insert_if(text, check, default=None)¶ Return text if check is
True; otherwise return default.
-
py314.formats.text.endl_if(check, n=1, default=None)¶ Return n endlines if check is
Trueand default otherwise.
-
py314.formats.text.spaces_if(check, n=1, default=None)¶ Return n spaces if check is
Trueand default otherwise.
Decorations¶
-
py314.formats.text.embrace(text, char, n=1)¶ Prefix and suffix text with a repeated char of length n.
-
py314.formats.text.quote(text, n=1)¶ Wrap text inside single backquotes.
-
py314.formats.text.halfquote(text)¶ Return `text’.
-
py314.formats.text.mixed(text)¶ Return `text’ and append a space before if needed
-
py314.formats.text.astrx(text, n=1)¶ Wrap text inside asterisks.
-
py314.formats.text.bold(text)¶ Return the string <b>text</b>.
-
py314.formats.text.boldu(text)¶ Return the string <u><b>text</b></u>.
-
py314.formats.text.boldit(text)¶ Return the string <i><b>text</b></i>.
-
py314.formats.text.bolditu(text)¶ Return the string <u><i><b>text</b></i></u>.
-
py314.formats.text.itshape(text, n=1)¶ Return the string <i>text</i>.
-
py314.formats.text.itshapeu(text)¶ Return the string <u><i>text</i></u>.
-
py314.formats.text.underlined(text)¶ Return the string <u>text</u>.
Document writer¶
-
class
py314.formats.document.Line¶ A formatted line. The line formatter takes as many arguments as slots and return a single string describing the line.
Parameters: -
static
__new__(cls, *slots, fmt=None, prefix='', raw=False)¶ Create and return a new object. See help(type) for accurate signature.
-
static
-
class
py314.formats.document.Section(*, fmt=None, prefix=None, style=None)¶ A list of
Linewith a common prefix, line format and style.Parameters: -
__str__()¶ A single string containing the joined lines.
-
fmt¶ str – The common line format.
-
prefix¶ str – The common line prefix.
-
reset()¶ Reset the section by removing all lines.
-
-
class
py314.formats.document.Document(page=None, *, fmt=None, prefix=None, style=None)¶ A document divided into sections. Positional arguments fmt, prefix and style denote a common document section format.
To change the format at runtime, call
change_format()with suitable arguments, or join the current document to another one.If page is not
None, callwrite()on all slots in page through self.write(*slots).Parameters: -
__str__()¶ Close the current section and return a single text.
-
__iadd__(other)¶ Join the sections of other to the current document. Only pushed will be joined and pushing the current stack if needed is left to the user.
Parameters: other (Document) – Another document
-
__deepcopy__(memodict=None)¶ Return a deep copy of this document.
-
clean_copy()¶ Return a clean copy of self. Equivalent to copy◦reset.
-
reset()¶ Reset the document by removing all sections.
-
blank_line()¶ Insert a blank line in the current section.
-
add_page(page)¶ Append all slots in the page to the current document.
Parameters: page (list) – A collection of valid unpackable slots.
-
write(*slots, prefix=None, raw=False, emphasize=False)¶ Delegate to
Section.write()to add a new line to the current section. If raw isTrue, no the line will not be formatted.If emphasize is
True, an endline characters is placed after the content by callingwrite()once with an empty string.
-
push_stack()¶ Push the current section to the current sections.
-
skip()¶ Push the current stack and start a new one with an endline.
Calling
pop()afterwards will remove the endline character.
-
change_format(fmt=None, prefix=None, style=None)¶ Close the current section if needed and change the common section formats with the new parameters. Changing the format will always open the current section and if nothing is added, an empty section will be added at the very end, which is not necessarily what you expect.
Parameters:
-
Page layout¶
-
py314.formats.page.columnize(mapping, per_page, *, ncols)¶ Given a
dict, namely mapping, return a generator pages, iterating over instances of tuples of tuples of strings, such that an instance ofDocument, say document, can be constructed and rendered as follows.The document is filled via document.write(*slots) as slots range over page, which range over pages. If slots has less than 2*ncols items, append to slots empty strings until it has a suitable length.
The number of rows in a page is always the greatest possible, but is always bounded from above by per_page. The number of columns ncols and is half the number of slots for a row, for a row alternates key and value during formatting.
Parameters:
Clean functions¶
This module provides functions to clean HTML text and brackets around numbers.
-
py314.formats.cleaner.clean_html(html_text)¶ Clean HTML escaped strings from html_text.
-
py314.formats.cleaner.clean_number(string_value)¶ Clean a number string_value in parenthesis.
Pretty print¶
-
py314.formats.pprint.pprint(obj, prefix = None)¶ If obj implement a
pprint()method, delegate the execution to it. Otherwise, use the genericstrobj()function.Parameters: prefix (str [optional]) – A string to prepend.
-
py314.formats.pprint.pprint(data, *, sep = ', ', prefix = None, sentinel = SENTINEL) Implemens the pretty print algorithm for
dict.Parameters: Seealso:
-
py314.formats.pprint.pprint(data, *, sep = ', ', prefix = None, sentinel = SENTINEL) Implemens the pretty print algorithm for the following classes:
Parameters: Seealso:
-
py314.formats.pprint.strobj(entity) Implement a surrogate of
__str__()for hashable objects.Seealso: strobj
-
py314.formats.pprint.strobj(function: typing.Callable) Implement a surrogate of
__str__()for callables objects.Seealso: strobj
-
py314.formats.pprint.pprintday(day)¶ Print the day number (
01is printed as1st, and so on).
Time formatting¶
Predefined time formats¶
-
class
py314.formats.time.FORMATS¶ Time format specifications namespace.
-
CLOCK¶ str – Usual clock format
%H:%M:%S.
-
ISO¶ str – Usual ISO format
%Y-%m-%d.
-
DATE¶ str – Contains
%A, %d %B %Y.
-
CRON¶ str – Contains
%d/%m/%Y @ %H:%M:%S.
-
DATETIME¶ str – Contains
%a, %d %b %Y at %H:%M:%S.
-
LONG¶ str – Contains
%A, %d %B %Y at %H:%M:%S.
-
Time formatters¶
-
py314.formats.time.strftime(value: int, *, fmt=None)¶ Convert a number of seconds value to a GMT time and then to a string according to a format specification fmt.
Parameters: - value (int) – Seconds since the UNIX epoch.
- fmt (str [optional]) – Format specification (default:
FORMATS.CLOCK).
-
py314.formats.time.strftimeat(timevalue=None, *, fmt=None)¶ Convert the time string timevalue or
datetime.datetime.now()to a string according to a format specification fmt.Parameters: - timevalue (int [optional]) – An optional time.
- fmt (str [optional]) – Format specification (default:
FORMATS.CLOCK).
-
py314.formats.time.strisodate(timevalue=None)¶ Partialization of
strftimeat()withFORMATS.ISOformat.
-
py314.formats.time.strcrontime(timevalue=None)¶ Partialization of
strftimeat()withFORMATS.CRONformat.
-
py314.formats.time.strdatetime(timevalue=None)¶ Partialization of
strftimeat()withFORMATS.DATETIMEformat.
-
py314.formats.time.strlongtime(timevalue=None)¶ Partialization of
strftimeat()withFORMATS.LONGformat.
-
py314.formats.time.print_seconds(seconds, *, prec=6)¶ Return a human-readable string representing the time-interval defined by seconds seconds.
Parameters: Examples
print_seconds(150) # 2 minutes, 30 seconds print_seconds(1500000, 2) # 2 weeks, 3 days print_seconds(1500000, 5) # 2 weeks, 3 days, 8 hours, 40 minutes