专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Python » 代码高亮:使用Pyments高亮显示代码为html »正文

代码高亮:使用Pyments高亮显示代码为html

来源: 发布时间:星期四, 2009年9月17日 浏览:18次 评论:0
  Pygments —— Python syntax highlighter (http://pygments.org/)

  首先要安装pygments代码  

easy_ pygments

  例子代码:

  Python代码  

#!/usr/bin/env python 
# encoding: utf-8 
""" 
code2html.py 
 
Created by Eric on 2009-09-14. 
Copyright (c) 2009 [email protected]__. 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', 
      noes="True") 
  result = highlight(code, lexer, formatter) 
   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') 
  pr html 
  ff = open('test.html','w') 
  ff.write(html) 
  ff.close 
 __name__  '____': 
  demo


0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: