编写Python脚本使得web页面上的代码高亮显示

WBOY
Release: 2016-06-10 15:14:26
Original
1472 people have browsed it

做了一个在线代码高亮的项目,强大的Python一如既往没让我失望,一个强大的Pygments模块可以对多种(很多)语言进行代码高亮

下面来介绍一下它:

首先安装很简单,使用easy_install来进行安装:

easy_install pygments

Copy after login

安装完后我们来使用,Python的简单不会让大家失望:

from pygments.lexers import PythonLexver
from pygments.formatters import HtmlFormatter
from pygments import highlight

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

print code

Copy after login

结果

'<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre class="brush:php;toolbar:false">1
Copy after login
<span class="k">print</span> <span class="s">"hello, world"</span>\n
Copy after login
\n'

这样就简单的对代码进行了高亮,当然如果你做了上面操作,然后把内容输入到一个文件里查看,肯定大呼坑爹,因为根本没高亮,因为默认是不会输出css的 我们还要获取css加入到html中去:

css = formatter.get_style_defs()

Copy after login

然后把css内容和上面的html一起写入到html文件就可以看到高亮的代码了(千万不要告诉我你不知道css应该放在什么位置)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template