开发学院软件开发Python 使用Pyments高亮显示代码为html 阅读

使用Pyments高亮显示代码为html

 2009-09-16 00:00:00 来源:WEB开发网   
核心提示:Pygments —— Python syntax highlighter (http://pygments.org/) 首先要安装pygments代码easy_installpygments实例代码: Python代码#!/usr/bin/envpython#encoding:utf-8&qu

Pygments —— Python syntax highlighter (http://pygments.org/)

首先要安装pygments代码  

easy_install pygments

实例代码:

Python代码  

#!/usr/bin/env python 
# encoding: utf-8 
""" 
code2html.py 
 
Created by Eric on 2009-09-14. 
Copyright (c) 2009 __lxneng@gmail.com__. All rights reserved. 
""" 
 
import sys 
from pygments import highlight 
from pygments.lexers import get_lexer_by_name 
from pygments.formatters import HtmlFormatter 
 
def code2html(code, lang): 
  lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True) 
  formatter = HtmlFormatter( 
      linenos=False, 
      encoding='utf-8', 
      noclasses="True") 
  result = highlight(code, lexer, formatter) 
  return result 
 
def demo(): 
  f = open(__file__) 
  code = f.read() 
  f.close() 
  html = """ 
 <html> 
   <head> 
     <title>Pygments_example</title> 
   </head> 
   <body> 
   %s 
 </body> 
 </html> 
 """%code2html(code, 'python') 
  print html 
  ff = open('test.html','w') 
  ff.write(html) 
  ff.close() 
if __name__ == '__main__': 
  demo()

Tags:使用 Pyments 高亮

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
更多精彩
    赞助商链接

    热点阅读
      焦点图片
        最新推荐
          精彩阅读