-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
54 lines (45 loc) · 1.55 KB
/
parser.py
File metadata and controls
54 lines (45 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import re
def convert_line(line: str) -> str:
"""
Parse the line to a heading, list item, a line of paragragh, et cetra
:param line: markdown line
:type line: str
:return: html line
:rtype: str
"""
# heading
if matches := re.search(r'^(#+)\s+(.*)', line):
level = len(matches.group(1))
text = matches.group(2)
if level <= 6:
return f"<h{level}>{text.strip()}</h{level}>"
else:
return f"<p>{text.strip()}</p>"
# unordered list item
elif matches := re.match(r'[ \t]*(\*|-|\+)\s+(.*)', line):
text = matches.group(2)
return f"<li>{text.strip()}</li>"
# ordered list item
elif re.match(r'[ \t]*\d+\.\s+', line):
text = line.split(maxsplit=1)[1]
return f"<li>{text.strip()}</li>"
# image
elif matches := re.search(r'!\[(.+?)\]\((\S+)(?:\s+"(.+)")?\)', line):
text, url, title = matches.groups()
if title:
return f'<img src="{url.strip()}" alt="{text.strip()}" title="{title.strip()}">'
else:
return f'<img src="{url.strip()}" alt="{text.strip()}">'
# table row
elif re.search(r'^(?:\|\s*([^|]+)\s*)+\|?$',line):
cells = [cell.strip() for cell in line.strip("|").split("|")]
tds = ""
for cell in cells:
tds += f"<td>{cell}</td>\n"
return f"<tr>\n{tds}</tr>"
# horizontal row
elif line == "---":
return f'<hr>'
# paragrapgh
else:
return f'<p>{line.strip()}</p>'