Important information: Google announced that, from September 2026, Android devices will require ALL apps to be signed by Google, effectively leading to an iOS situation. Value your right to a computer that does what you want; do not tolerate this monopolistic practice! Contact me if you don't understand why it is bad. Click to learn more.

 syntax_colouring.py

View raw Download
text/x-script.python • 2.13 kiB
Python script, ASCII text executable
        
            
1
from pygments import highlight
2
from pygments.style import Style
3
from pygments import token
4
from pygments.lexers import PythonLexer
5
from pygments.formatters import HtmlFormatter
6
from bs4 import BeautifulSoup
7
8
9
class CustomStyle(Style):
10
default_style = ""
11
styles = {
12
token.Text: "",
13
token.Keyword: "bold #ff9800",
14
token.Name: "",
15
token.Operator: "",
16
17
token.Name.Class: "#ffeb3b",
18
token.Name.Function: "#be9ddb",
19
token.Name.Builtin: "#ab47bc",
20
token.Name.Attribute: "#4db6ac",
21
token.Name.Constant: "italic #ef5350",
22
token.Name.Decorator: "#bcaaa4",
23
token.Name.Function.Magic: "#e040fb",
24
token.Name.Label: "#ff4081",
25
26
token.String: "#8bc34a",
27
token.Number: "#42a5f5",
28
token.Punctuation: "#ff9800",
29
token.Comment: "italic #b0bec5",
30
token.Generic: "",
31
token.Escape: "#ff5722",
32
token.String.Escape: "#ff5722",
33
token.String.Regex: "#ffffff",
34
token.Comment.Preproc: "#536dfe",
35
token.Comment.Hashbang: "#536dfe",
36
token.Error: "#f44336",
37
token.Other: "",
38
token.Whitespace: "",
39
}
40
41
42
code = """
43
___all___ = ["hello_world"]
44
45
def interesting_function(func: Callable) -> Callable:
46
\"\"\"Print the function's result when called.
47
48
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec nulla
49
nec nulla laoreet fermentum. Integer id lacus ut odio interdum ultricies.
50
\"\"\"
51
def wrapper(*args, **kwargs):
52
result = func(*args, **kwargs) # avoid double evaluation
53
print(result)
54
return result
55
return wrapper
56
57
@interesting_function
58
def hello_world():
59
return "Hello, world!\\a" # a nice bell
60
61
if __name__ == "__main__":
62
hello_world()
63
"""
64
65
lexer = PythonLexer()
66
formatter = HtmlFormatter(style="colorful")
67
html_code = highlight(code, lexer, formatter)
68
69
soup = BeautifulSoup(html_code, "html.parser")
70
pre = soup.find("pre")
71
lines = pre.decode_contents().splitlines()
72
73
for line in lines:
74
line_soup = BeautifulSoup(line, "html.parser")
75
clean_line = line_soup.prettify()
76
print(clean_line)
77