国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

如何用Python實現簡單的Markdown轉換器

2020-02-15 22:25:22
字體:
來源:轉載
供稿:網友

今天心血來潮,寫了一個 Markdown 轉換器。

import os, re,webbrowsertext = '''# TextHeader ## Header1  List   - 1    - 2   - 3  > **quote**  》 quote2 ## Header2  1. *斜體*  2. [@以茄之名](https://www.jb51.net/people/e4f87c3476a926c1e2ef51b4fcd18fa3)  3、 ![](https://www.jb51.net/v2-8560440c136c746730a63813ed701f52_is.jpg)   ## 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

這里我稍微修改了一點,讓 > 和 》 都可以轉換成引用,主要是切換中英文標點太難了。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 霸州市| 东港市| 甘南县| 栾川县| 安仁县| 永兴县| 铜陵市| 普定县| 博湖县| 沙湾县| 泾源县| 双城市| 定南县| 晋宁县| 合阳县| 平远县| 台北县| 临安市| 大渡口区| 莎车县| 灵璧县| 库车县| 龙川县| 宁津县| 甘洛县| 高要市| 竹溪县| 汾阳市| 徐汇区| 彰化市| 白玉县| 英吉沙县| 沽源县| 石楼县| 青浦区| 丰宁| 虎林市| 平江县| 高邑县| 乌兰浩特市| 岱山县|