用Python對各種編程語言進行源碼高亮

下邊代碼段是關於用Python對各種編程語言進行高亮的代碼。

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</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>'

這樣就簡單的對代碼進行了高亮,當然如果你做了上面操作,然後把內容輸入到一個文件裏查看,肯定大呼坑爹,因爲根本沒高亮,因爲默認是不會輸出css的我們還要獲取css加入到html中去:

css = formatter.get_style_defs()

然後把css內容和上面的html一起寫入到html文件就可以看到高亮的代碼了(千萬不要告訴我你不知道css應該放在什麼位置)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章