forked from tate233/todolist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown_parser.py
More file actions
193 lines (162 loc) · 6.73 KB
/
markdown_parser.py
File metadata and controls
193 lines (162 loc) · 6.73 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Last modified at 2026/05/24 星期日 15:04:02
import re
from typing import Dict, List, Tuple
import markdown
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.util import ClassNotFound
class MarkdownParser:
def __init__(self):
self.md = markdown.Markdown(extensions=[
'extra',
'codehilite',
'tables',
'fenced_code',
'toc'
])
self.heading_pattern = re.compile(r'^(#{1,6})\s+(.+)$', re.MULTILINE)
self.link_pattern = re.compile(r'\[([^\]]+)\]\(([^\)]+)\)')
self.image_pattern = re.compile(r'!\[([^\]]*)\]\(([^\)]+)\)')
self.code_block_pattern = re.compile(r'```(\w+)?\n(.*?)```', re.DOTALL)
self.bold_pattern = re.compile(r'\*\*(.+?)\*\*|__(.+?)__')
self.italic_pattern = re.compile(r'\*(.+?)\*|_(.+?)_')
self.list_pattern = re.compile(r'^[\*\-\+]\s+(.+)$', re.MULTILINE)
self.task_pattern = re.compile(r'^\s*[-*]\s+\[([ x])\]\s+(.+)$', re.MULTILINE)
def parse_to_html(self, text: str) -> str:
try:
html = self.md.convert(text)
self.md.reset()
return html
except Exception as e:
print(f"Markdown解析失败: {e}")
return f"<pre>{text}</pre>"
def extract_headings(self, text: str) -> List[Tuple[int, str]]:
headings = []
for match in self.heading_pattern.finditer(text):
level = len(match.group(1))
title = match.group(2).strip()
headings.append((level, title))
return headings
def extract_links(self, text: str) -> List[Tuple[str, str]]:
links = []
for match in self.link_pattern.finditer(text):
link_text = match.group(1)
link_url = match.group(2)
links.append((link_text, link_url))
return links
def extract_images(self, text: str) -> List[Tuple[str, str]]:
images = []
for match in self.image_pattern.finditer(text):
alt_text = match.group(1)
image_url = match.group(2)
images.append((alt_text, image_url))
return images
def extract_code_blocks(self, text: str) -> List[Tuple[str, str]]:
code_blocks = []
for match in self.code_block_pattern.finditer(text):
language = match.group(1) or 'text'
code = match.group(2).strip()
code_blocks.append((language, code))
return code_blocks
def extract_tasks(self, text: str) -> List[Tuple[bool, str]]:
tasks = []
for match in self.task_pattern.finditer(text):
is_completed = match.group(1).lower() == 'x'
task_text = match.group(2).strip()
tasks.append((is_completed, task_text))
return tasks
def get_word_count(self, text: str) -> int:
text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)
text = re.sub(r'`[^`]+`', '', text)
text = re.sub(r'[#\*\-\[\]\(\)_]', '', text)
words = text.split()
return len(words)
def get_reading_time(self, text: str, words_per_minute: int = 200) -> int:
word_count = self.get_word_count(text)
minutes = max(1, round(word_count / words_per_minute))
return minutes
def highlight_code(self, code: str, language: str = 'python') -> str:
try:
lexer = get_lexer_by_name(language, stripall=True)
except ClassNotFound:
try:
lexer = guess_lexer(code)
except:
lexer = get_lexer_by_name('text')
formatter = HtmlFormatter(style='monokai', noclasses=True)
return highlight(code, lexer, formatter)
def create_toc(self, text: str) -> str:
headings = self.extract_headings(text)
if not headings:
return ""
toc = "## 目录\n\n"
for level, title in headings:
indent = " " * (level - 1)
anchor = title.lower().replace(' ', '-')
toc += f"{indent}- [{title}](#{anchor})\n"
return toc
def add_syntax_highlighting(self, text: str) -> str:
def replace_code_block(match):
language = match.group(1) or 'text'
code = match.group(2).strip()
highlighted = self.highlight_code(code, language)
return f'<div class="code-block">{highlighted}</div>'
return self.code_block_pattern.sub(replace_code_block, text)
def extract_metadata(self, text: str) -> Dict:
lines = text.split('\n')
metadata = {}
if lines and lines[0].strip() == '---':
i = 1
while i < len(lines) and lines[i].strip() != '---':
line = lines[i].strip()
if ':' in line:
key, value = line.split(':', 1)
metadata[key.strip()] = value.strip()
i += 1
return metadata
def format_markdown(self, text: str) -> str:
lines = text.split('\n')
formatted_lines = []
in_code_block = False
for line in lines:
t = line.strip()
if t.startswith('```'):
in_code_block = not in_code_block
t = line
elif in_code_block:
t = line
else:
t = line.rstrip()
formatted_lines.append(t)
return '\n'.join(formatted_lines)
def convert_to_plain_text(self, text: str) -> str:
text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)
text = re.sub(r'`[^`]+`', '', text)
text = re.sub(r'!\[([^\]]*)\]\([^\)]+\)', r'\1', text)
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
text = re.sub(r'[#\*\-_]', '', text)
text = re.sub(r'\n{3,}', '\n\n', text)
return text.strip()
def search_in_markdown(self, text: str, keyword: str) -> List[Tuple[int, str]]:
if not keyword:
return []
keyword = keyword.lower()
results = []
lines = text.split('\n')
for i, line in enumerate(lines, 1):
if keyword in line.lower():
results.append((i, line.strip()))
return results
def get_statistics(self, text: str) -> Dict:
return {
'word_count': self.get_word_count(text),
'char_count': len(text),
'line_count': len(text.split('\n')),
'heading_count': len(self.extract_headings(text)),
'link_count': len(self.extract_links(text)),
'image_count': len(self.extract_images(text)),
'code_block_count': len(self.extract_code_blocks(text)),
'task_count': len(self.extract_tasks(text)),
'reading_time': self.get_reading_time(text)
}