今天心血來潮,寫了一個 Markdown 轉換器。
import os, re,webbrowsertext = '''# TextHeader ## Header1 List - 1 - 2 - 3 > **quote** 》 quote2 ## Header2 1. *斜體* 2. [@以茄之名](https://www.jb51.net/people/e4f87c3476a926c1e2ef51b4fcd18fa3) 3、  ## Header3 `*[文章地址](https://zhuanlan.zhihu.com/p/39742445)*` ·**code1**· - [x]是否點贊'''
程序開頭先處理一些行內的語法,比如 code、strong、i 等,用正則直接替換:
text = re.sub(re.compile('([/`·])([^`·]+)[/`·]'), r'<code>/2</code>', text)text = re.sub(re.compile('/*/*([^/*]+)/*/*'), r'<strong>/1</strong>', text)text = re.sub(re.compile('([^/*])/*([^/*]+)/*'), r'/1<i>/2</i>', text)
接著是復雜一點的圖片和鏈接:
text = re.sub(re.compile('([^/!])/[([^/]]+)/]/(([^)]+)/)'), r'/1<a href="/3" rel="external nofollow" target="_blank">/2</a>', text)text = re.sub(re.compile('/!/[([^/]]*)/]/(([^)]+)/)'), r'<img src="/2" >', 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 += '''<label class="cssCheckbox"> <input type="checkbox" %s /> <span></span>%s </label>''' % (p_html, line)
因為有序列表和無序列表的區別是頭尾的ol和ul,所以要用 list_flag 變量來判斷
elif re.match('[/+/-/*] ', line): if list_flag == '': html += '<ul>/n' list_flag = 'ul' line = re.sub('[/+/-/*] ', '', line) html += '<li>%s</li>/n' % (line)elif re.match('[/d]+[.、] ', line): if list_flag == '': list_flag = 'ol' html += '<ol>/n' line = re.sub('[/d]+[.、] ', '', line) html += '<li>%s</li>/n' % (line)
處理完后處理其他的語法:
else: if list_flag != '': html += '</%s>/n' % list_flag list_flag = '' if re.match('/#+', line): well = re.match('/#+', line).group().count('#') line = re.sub('/#+', '', line) html += '<h%i>%s</h%i>/n' % (well, line, well) elif re.match('[>》 ]', line): line = re.sub('^/s*[>》 ]', '', line) html += '<blockquote>%s</blockquote>/n' % (line) # elif re.match('[>》 ]', line): # line = re.sub('^/s*[>》 ]', '', line) # html += '<blockquote>%s</blockquote>/n' % (line) else: html += line
這里我稍微修改了一點,讓 > 和 》 都可以轉換成引用,主要是切換中英文標點太難了。
新聞熱點
疑難解答