做了一个在线代码高亮的项目,因为写的Gtalk群Bot需要这个功能支持,贴到第三方怕被人给封,所以干脆想自己写一个,强大的Python一如既往没让我失望,一个强大的Pygments模块可以对多种(很多)语言进行代码高亮
转自:http://www.linuxzen.com/index.php/archives/377
下面来介绍一下它:
首先安装很简单,使用easy_install来进行安装:
easy_install pygments
安装完后我们来使用,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
##### 结果 ################
'<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
