編寫Python指令碼使得web頁面上的代碼高亮顯示

來源:互聯網
上載者:User
做了一個線上代碼高亮的項目,強大的Python一如既往沒讓我失望,一個強大的Pygments模組可以對多種(很多)語言進行代碼高亮

下面來介紹一下它:

首先安裝很簡單,使用easy_install來進行安裝:

easy_install pygments

安裝完後我們來使用,Python的簡單不會讓大家失望:

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

結果

'
 
1
print "hello, world"\n
\n
'

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

css = formatter.get_style_defs()

然後把css內容和上面的html一起寫入到html檔案就可以看到高亮的代碼了(千萬不要告訴我你不知道css應該放在什麼位置)

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.