如何用Python实现简单的Markdown转换器 今天心血来潮,写了一个 Markdown 转换器。 import os, re,webbrowser text = ''' # TextHeader ## Header1 List - 1 - 2 - 3 > **quote** 》 quote2 ## Header2 1. *斜体* 2. [@以茄之名](http://www.zwyuanma.com/people/e4f87c3476a926c1e2ef51b4fcd18fa3) 3、 ![](http://www.zwyuanma.com/v2-8560440c136c746730a63813ed701f52_is.jpg) ## Header3 `*[文章地址](http://zhuanlan.zhihu.com/p/39742445)*` ·**code1**· - [x]是否点赞 ''' 程序开头先处理一些行内的语法,比如 code、strong、i 等,用正则直接替换: text = re.sub(re.compile('([\`·])([^`·]+)[\`·]'), r'\2', text) text = re.sub(re.compile('\*\*([^\*]+)\*\*'), r'\1', text) text = re.sub(re.compile('([^\*])\*([^\*]+)\*'), r'\1\2', text) 接着是复杂一点的图片和链接: text = re.sub(re.compile('([^\!])\[([^\]]+)\]\(([^)]+)\)'), r'\1\2', text) text = re.sub(re.compile('\!\[([^\]]*)\]\(([^)]+)\)'), r'', text) 接着就处理其他的语法,先把文本按每一行分开: lines = text.split('\n') html = '' list_flag = '' 处理列表和待办事项的问题: for line in lines: line = line.strip(' ') if re.match('- \[[ x]\]', line): print('matched') p_html = '' if re.match('- \[x\]', line): p_html = ' checked="checked"' line = re.sub('- \[[ x]\]', '', line) html += '''''' % (p_html, line) 因为有序列表和无序列表的区别是头尾的ol和ul,所以要用 list_flag 变量来判断 elif re.match('[\+\-\*] ', line): if list_flag == '': html += '