This article mainly introduces how to compile a Python script to highlight the code on the web page. it mainly uses the pygments tool. if you need it, you can refer to the following online code highlighting project, powerful Python, as always, does not disappoint me. a powerful Pygments module can highlight code in multiple (many) languages.
Here we will introduce it:
The installation is simple first, and easy_install is used for installation:
easy_install pygments
We will use Python after installation. the simplicity of Python won't disappoint everyone:
from pygments.lexers import PythonLexverfrom pygments.formatters import HtmlFormatterfrom pygments import highlightformatter = HtmlFormatter(encoding='utf-8', style = 'emacs', linenos = True)code = highlight('print "hello, world"', PythonLexer(), formatter)print code
Result
'
1 |
print "hello, world"\n \n |
'
In this way, the code is simply highlighted. of course, if you do the above operations and input the content into a file to view the content, you must be confused, because there is no highlight at all, because css is not output by default, we also need to get css and add it to html:
css = formatter.get_style_defs()
Then write the css content and the preceding html content into the html file to see the highlighted code (do not tell me where you do not know the css should be placed)