Skip to content

Instantly share code, notes, and snippets.

@hanxiaomax hanxiaomax/GFM2pyg.py

Last active Aug 29, 2015
Embed
What would you like to do?
静态方法/装饰器
#coding=utf-8
#使用静态方法,装饰器
from sys import argv
import sys
import glob
import os
script,language=argv#return as strings
#TODO:行号
path=os.path.abspath(sys.argv[0])
print path
# print glob.glob(path+r"\../*.md")
class HighLightTrans(object):
"""把GFM风格的代码高亮转换为Pygments风格"""
@staticmethod
def GFM2PYG(filename):
is_start=True
dest=open("_"+filename,'w')
with open(filename,'r') as f:
for line in f:
line=line.strip('\n')
if ("```" or "~~~") in line :#注意要加括号
if is_start is True:
dest.write("{% highlight "+language+"%}"+"\n")
is_start=False
elif is_start is False:
dest.write("{% endhighlight %}"+"\n")
is_start=True
else:
pass
else:
dest.write(line+"\n")
for filename in glob.glob(path+r"\../*.md"):
filename=os.path.basename(filename)
HighLightTrans.GFM2PYG(filename)
#coding=utf-8
#使用类成员方法
from sys import argv
import sys
import glob
import os
script,language=argv#return as strings
#TODO:行号
path=os.path.abspath(sys.argv[0])
print path
# print glob.glob(path+r"\../*.md")
class HighLightTrans(object):
"""把GFM风格的代码高亮转换为Pygments风格"""
def GFM2PYG(self,filename):
self.is_start=True
dest=open("_"+filename,'w')
with open(filename,'r') as f:
for line in f:
line=line.strip('\n')
if ("```" or "~~~") in line :#注意要加括号
if self.is_start is True:
dest.write("{% highlight "+language+"%}"+"\n")
self.is_start=False
elif self.is_start is False:
dest.write("{% endhighlight %}"+"\n")
self.is_start=True
else:
pass
else:
dest.write(line+"\n")
for filename in glob.glob(path+r"\../*.md"):
filename=os.path.basename(filename)
hightlight=HighLightTrans()
hightlight.GFM2PYG(filename)

###类成员方法 在类里面定义的函数,一般都是类成员方法,包含一个self参数,调用的时候必须通过实例来调用

for filename in glob.glob(path+r"\../*.md"):
	filename=os.path.basename(filename)
	hightlight=HighLightTrans()
	hightlight.GFM2PYG(filename)

###静态方法 其实和类没什么关系,只是封装在类里面而已,需要用装饰器@staticmethod来说明,调用的时候可以直接类似A.a()这样调用

for filename in glob.glob(path+r"\../*.md"):
	filename=os.path.basename(filename)
	HighLightTrans.GFM2PYG(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.