我在写博客《Linux的1000个命令》的时候,相对二级标题进行一下排序,方便阅读和查找,于是就有了这个小程序。
#! /usr/bin/env python3
import os
import subprocess
class BaseMethod:
@staticmethod
def run_cmd(cmd):
retcode, output = subprocess.getstatusoutput(cmd)
return retcode, output
@staticmethod
def write_file(filename, content):
with open(filename, 'w', encoding='UTF-8')as tf:
tf.write(content)
@staticmethod
def read_file(file_name, mode="r"):
if not os.path.exists(file_name):
raise IOError("No such file or directory: %s" % file_name)
with open(file_name, mode, encoding='UTF-8')as fp:
content = fp.read()
return content
f="linux.md"
class SortMD:
def __init__(self, filename):
# self.filename = filename
self.content = BaseMethod.read_file(filename)
self.data = {}
def split_now(self):
sharp2 = self.content.split('##')
for i in sharp2:
if i.startswith('#'):
self.data['sharp1'] = i
else:
if 'sharp2' in self.data.keys():
self.data['sharp2'].append('## '+i.strip('
'))
else:
self.data['sharp2'] = ['##' + i.strip('
')]
print(self.data)
self.data['sharp2'].sort()
print(self.data)
def save2file(self, name):
s1 = self.data['sharp1']
s2 = "
".join(self.data['sharp2'])
data = s1 + s2
print(data)
BaseMethod.write_file(name, data)
def main():
md = SortMD(f)
md.split_now()
md.save2file("new.md")
if __name__ == "__main__":
main()