pip install Pygments
python
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
python
lexer = get_lexer_by_name('python')
python
code = """
def greet():
print("Hello, World!")
greet()
"""
highlighted_code = highlight(code, lexer, HtmlFormatter())
python
with open('highlighted_code.html', 'w') as f:
f.write(highlighted_code)
python
custom_formatter = HtmlFormatter(
style='default',
linenos=True,
full=True,
cssclass='code-highlight',
cssfile='custom.css'
)
python
highlighted_code = highlight(code, lexer, custom_formatter)
html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="custom.css">
</head>
<body>
</body>
</html>