做了一個在線代碼高亮的項目,強大的Python一如既往沒讓我失望,一個強大的Pygments模塊可以對多種(很多)語言進行代碼高亮
下面來介紹一下它:
首先安裝很簡單,使用easy_install來進行安裝:
1
|
easy_install pygments |
安裝完后我們來使用,Python的簡單不會讓大家失望:
1
2
3
4
5
6
7
8
|
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 |
結果
1
|
'< 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" >"hello, world"</ span >\n</ pre ></ div >\n</ td ></ tr ></ table >' |
這樣就簡單的對代碼進行了高亮,當然如果你做了上面操作,然后把內容輸入到一個文件里查看,肯定大呼坑爹,因為根本沒高亮,因為默認是不會輸出css的 我們還要獲取css加入到html中去:
1
|
css = formatter.get_style_defs() |
然后把css內容和上面的html一起寫入到html文件就可以看到高亮的代碼了(千萬不要告訴我你不知道css應該放在什么位置)