用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应该放在什么位置)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值