用Python对各种编程语言进行源码高亮

下边代码段是关于用Python对各种编程语言进行高亮的代码。

邢台县ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

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
##### 结果 ################
'
1
print "hello, world"n
n
' 这样就简单的对代码进行了高亮,当然如果你做了上面操作,然后把内容输入到一个文件里查看,肯定大呼坑爹,因为根本没高亮,因为默认是不会输出css的我们还要获取css加入到html中去: css = formatter.get_style_defs() 然后把css内容和上面的html一起写入到html文件就可以看到高亮的代码了(千万不要告诉我你不知道css应该放在什么位置)

网页标题:用Python对各种编程语言进行源码高亮
本文链接:http://myzitong.com/article/pecedh.html