国产探花免费观看_亚洲丰满少妇自慰呻吟_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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永州市| 宁化县| 星子县| 梁山县| 定安县| 琼海市| 宿松县| 南充市| 崇阳县| 麻栗坡县| 闽侯县| 乐昌市| 二连浩特市| 益阳市| 黔南| 千阳县| 平果县| 临武县| 大连市| 盘锦市| 任丘市| 瑞丽市| 黔东| 成武县| 吐鲁番市| 金寨县| 宜州市| 赣榆县| 夏津县| 尉氏县| 郑州市| 富裕县| 长岭县| 囊谦县| 波密县| 丰顺县| 安平县| 澜沧| 堆龙德庆县| 建湖县| 海兴县|