Skip to content

Instantly share code, notes, and snippets.

@tuanchauict
Last active July 28, 2022 05:26
Show Gist options
  • Save tuanchauict/b4d542c22fc8c63625522177cf38dcfe to your computer and use it in GitHub Desktop.
Save tuanchauict/b4d542c22fc8c63625522177cf38dcfe to your computer and use it in GitHub Desktop.
A simple script for formatting text
import re
text_formats = ['b', 'i', 'u', 'f']
dark_colors = ["black", "red", "green", "yellow", "blue",
"magenta", "cyan", "gray"]
light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
"brightmagenta", "brightcyan", "white"]
def code(number):
return f"\x1b[{number:02d}m"
codes = {
'</t>': code(0), # End text format
"</c>": code(39), # End foreground color
"</b>": code(49), # End background color
}
for i, text_format in enumerate(text_formats):
codes[f"<{text_format}>"] = code(i + 1)
for i, (dark, light) in enumerate(list(zip(dark_colors, light_colors))):
codes[f"<{dark}>"] = code(i + 30)
codes[f"<{light}>"] = code(i + 90)
codes[f"<b:{dark}>"] = code(i + 40)
codes[f"<b:{light}>"] = code(i + 100)
def textformat(template, enabled=True):
arr = re.split(r"(<.+?>)", template)
for i, text in enumerate(arr):
if text in codes:
arr[i] = codes[text] if enabled else ""
return "".join(arr)
if __name__ == '__main__':
print(textformat("<b><b:red>home</b></c> is</t> <i>a <green>place</c> to <b><u>sleep</t>"))
print(textformat("<b><b:red>home</b></c> is</t> <i>a <green>place</c> to <b><u>sleep</t>", enabled=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment