SoFunction
Updated on 2024-10-29

Write Python scripts to highlight code on web pages.

did an online code highlighting project , the powerful Python as always did not let me down , a powerful Pygments module can be on a variety of (many) languages for code highlighting

Here's a little bit about it.

First of all the installation is very simple, use easy_install to install.

easy_install pygments

Once installed, let's get started. Python's simplicity doesn't disappoint.

from  import PythonLexver
from  import HtmlFormatter
from pygments import highlight

formatter = HtmlFormatter(encoding='utf-8', style = 'emacs', linenos = True)
code = highlight('print "hello, world"', PythonLexer(), formatter)

print code

in the end

'<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre><span class="k">print</span> <span class="s">&quot;hello, world&quot;</span>\n</pre></div>\n</td></tr></table>'

This is simple to highlight the code, of course, if you do the above operation, and then the contents of the input to a file to view, must be shouting pitfalls, because there is no highlighting, because the default is not the output of css We also want to get the css to add to the html to go.

css = formatter.get_style_defs()

Then write the css content to the html file along with the html above to see the highlighted code (don't ever tell me you don't know where the css should go)