Compile a Python script to highlight the code on the web page

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.