用Python格式化MarkDown文件

Posted by Kerwen Blog on March 27, 2016

最近在学习Python, 尝试用Python去做各种小程序。其中一个想做的就是格式化MD文件。由于博客建在Github上,所以文章一般都是用MarkDown写的。但MarkDown有些语法规则让我很不习惯。比如: 一行的末尾要加两个空格, 代码前后要加空行分开,本人比较懒,所以干脆就写个脚本来统一格式化一下。
直接上代码,有空再逐步优化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
''' 
This script is used to format MarkDown file.
1. Add blank space for each line
2. If meet code, add tab and \r automatically
3. Add markdown header automatically, include create time
'''

# -*- coding: utf-8 -*-

#---------------------------------------------------------------

# Read data from a file

def ReadMDFile (strFilePath):
	message=""

	# check file path existance	

	import os
	result = os.path.isfile(strFilePath)
	if( result == False ):
		message= "Could not find the file. Please check again."
		return "",False,message
	
	# read the date to a string list

	fo = open(strFilePath,"r", encoding="utf-8")
	fileData = fo.readlines()
	fo.close()
	return fileData,True,message

#----------------------------------------------------------------	

# Check MD style header existance

def IsHeaderExist(fileList):
	if fileList[0] == "---\n" and fileList[6] == "---\n":
		return True
	else:
		return False
		
	
#----------------------------------------------------------------	

# Generate MarkDown header

def GenerateHeader(title, categories, tags):
	header = ["---","layout: post", "title: ", "date:   ", "categories: ", "catalog: true tags: ", "---", "", "* content", "{:toc}", ""]
	header[2] += title
	
	# Get current time

	import datetime;
	currentTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
	header[3] += currentTime
	
	#categories

	header[4] += "[" + categories + "]"
	
	# tags

	tags = "[" + tags +"]"
	header[5] += tags
	return header

#----------------------------------------------------------------	

# Format contents, add space for each description line, add white line for code's begin and end

def FormatData(lineData):
	length = len(lineData);
	index=0
	while (index < length):
		line = lineData[index].strip('\n')
		if(IsWhiteLine(line)):
			index +=1
			continue
		
		if IsHeader(line):
			if IsNotLastLine(index, length) :
				if (IsWhiteLine(lineData[index + 1]) is False):				
					lineData.insert(index + 1,"\n")
					length +=1
			index +=1
			continue
			
		if IsCodeLine(line):
			if IsNotLastLine(index, length) :
				if (IsDescription(lineData[index + 1]) or IsHeader(lineData[index + 1])):
					lineData.insert(index + 1,"\n")
					length +=1
			index += 1
			continue
		
		if line.endswith("   ") is False:
			line += "   "		
		if IsNotLastLine(index, length):
			if (IsCodeLine(lineData[index +1]) or IsHeader(lineData[index + 1])):
				lineData.insert(index +1, "\n")
				length += 1
			lineData[index] = line + "\n"		
		index +=1
	return

#----------------------------------------------------------------	

def IsHeader(line):
	line = line.strip()
	if line.startswith("#") or line.startswith("##") or line.startswith("###") or line.startswith("####"):
		return True
	return False

#----------------------------------------------------------------		

def IsWhiteLine(line):
	if(len(line.strip()) is 0):
		return True
	return False

#----------------------------------------------------------------		

def IsCodeLine(line):
	if(line[0] == "\t" ):
		return True
	return False

#----------------------------------------------------------------		

def IsDescription(line):
	if(IsWhiteLine(line) is False):
		if(IsCodeLine(line) is False):
			if IsHeader(line) is False:
				return True
	return False

#----------------------------------------------------------------		

def IsNotLastLine(index, length):
	if index < length -1:
		return True
	return False

#----------------------------------------------------------------	

def IsSubString(SubStrList,Str):  
	''''' 

	#判断字符串Str是否包含序列SubStrList中的某一个子字符串 

	#>>>SubStrList=['F','EMS','txt'] 

	#>>>Str='F06925EMS91.txt' 

	#>>>IsSubString(SubStrList,Str)#return True  

	'''  
	for substr in SubStrList:  
		if (substr in Str):  
			return True  
  
	return False  

#----------------------------------------------------------------	

def GetFileList(FindPath,FlagStr=[]):  
	''''' 

	#获取目录中指定的文件名 

	#>>>FlagStr=['F','EMS','txt'] #要求文件名称中包含这些字符 

	#>>>FileList=GetFileList(FindPath,FlagStr) # 

	'''  
	import os  
	FileList=[]  
	FileNames=os.listdir(FindPath)  
	if (len(FileNames)>0):  
	   for fn in FileNames:  
		   if (len(FlagStr)>0):  

			   #返回指定类型的文件名  

			   if (IsSubString(FlagStr,fn)):  
				   fullfilename=os.path.join(FindPath,fn)  
				   FileList.append(fullfilename)  
		   else:  

			   #默认直接返回所有文件名  

			   fullfilename=os.path.join(FindPath,fn)  
			   FileList.append(fullfilename)  
  
	#对文件名排序  

	if (len(FileList)>0):  
		FileList.sort()  
  
	return FileList  	

#----------------------------------------------------------------

def FormatMDFile(filePath):
	linelists,result,message = ReadMDFile(filePath)
	if (result == False):
		print (message)
		return -1

	result = IsHeaderExist(linelists)

	if result is False :

		# Add MD header

		title = linelists[0].strip('\n')
		categories = linelists[1].strip('\n')
		tags = linelists[2].strip('\n')
		header = GenerateHeader(title, categories, tags)
		for index in range(len(header)):
			header[index] += "\n"
	
		lineData = linelists[4:]
	else:
		header = linelists[0:11]
		lineData = linelists[11:]

	# Format each line

	FormatData(lineData)

	newLinelists = header + lineData

	if newLinelists==linelists:
		return 0
	fo = open(filePath,"w", encoding="utf-8")
	fo.writelines(newLinelists)
	fo.close()
	return 1

#----------------------------------------------------------------

# Main Entry

import os
folder = "E:\\kerwenzhang.github.io\\_posts"
fileFlag = [".md",".txt"]
FileLists = GetFileList(folder, fileFlag)

fileListChanged =[]
for file in FileLists:
	result = FormatMDFile(file)
	if (result < 0):
		print ("Failed to format file : ", file)
		exit()
	else:
		if(result > 0):
			fileListChanged.append(file)			

if len(fileListChanged) == 0 :
	print ("No file need to be formated.")
	exit()

print ("Following files have been formated:")
for file in fileListChanged:
	print (file)
print("\n")
print("---------------------------")
print("Total Num:", len(fileListChanged))