Skip to content

Commit 8a2528a

Browse files
committed
feat:添加代码提取工具
1 parent 90caa8b commit 8a2528a

File tree

4 files changed

+126
-0
lines changed

4 files changed

+126
-0
lines changed
1.11 KB
Binary file not shown.

tools/fragment/README.md

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# 代码片段提取工具
2+
3+
## 简介
4+
代码片段提取工具是一个专门用于从 Markdown 格式文本中提取特定语言代码块的 Python 函数。
5+
6+
## 功能特性
7+
- **精准提取**:使用正则表达式精准匹配 Markdown 代码块
8+
- **格式保持**:完整保留代码块内部的格式和缩进
9+
- **多语言支持**:支持提取任意编程语言的代码片段
10+
- **简单易用**:清晰的 API 接口,一行代码即可完成提取
11+
12+
## 核心函数
13+
14+
```python
15+
def main(input_str: str, split_str: str) -> str | None:
16+
"""
17+
从 Markdown 文本中提取指定语言的代码块内容
18+
19+
Args:
20+
input_str: 输入的 Markdown 格式文本
21+
split_str: 要提取的代码块语言标识
22+
23+
Returns:
24+
成功时返回提取的代码内容,未找到匹配时返回 None
25+
"""
26+
pattern = r'```'+split_str+'\s*\n(.*?)\n\s*```'
27+
match = re.search(pattern, input_str, re.DOTALL)
28+
if match:
29+
content = match.group(1).strip('\n')
30+
return content
31+
return None
32+
33+
```
34+
35+
# 使用示例
36+
示例 1:提取 json 数据
37+
38+
提取前:
39+
```json
40+
{
41+
"database": {
42+
"host": "localhost",
43+
"port": 5432,
44+
"name": "myapp"
45+
},
46+
"server": {
47+
"port": 8080,
48+
"debug": true
49+
},
50+
"features": ["auth", "upload", "api"]
51+
}
52+
```
53+
54+
提取后:
55+
去掉了 ```json ``` 的标识,方便后续接口传参
56+
57+
{
58+
"database": {
59+
"host": "localhost",
60+
"port": 5432,
61+
"name": "myapp"
62+
},
63+
"server": {
64+
"port": 8080,
65+
"debug": true
66+
},
67+
"features": ["auth", "upload", "api"]
68+
}
69+
70+
示例 2:提取 sql 语句
71+
72+
提取前:
73+
74+
```sql
75+
SELECT
76+
u.id,
77+
u.username,
78+
u.email,
79+
COUNT(o.id) as order_count
80+
FROM
81+
users u
82+
LEFT JOIN
83+
orders o ON u.id = o.user_id
84+
WHERE
85+
u.created_at >= '2024-01-01'
86+
AND u.status = 'active'
87+
GROUP BY
88+
u.id, u.username, u.email
89+
HAVING
90+
COUNT(o.id) > 5
91+
ORDER BY
92+
order_count DESC
93+
LIMIT 10;
94+
```
95+
96+
提取后:
97+
98+
去掉了 ```sql ``` 的标识,后面直接对接sql函数查询即可。
99+
100+
SELECT
101+
u.id,
102+
u.username,
103+
u.email,
104+
COUNT(o.id) as order_count
105+
FROM
106+
users u
107+
LEFT JOIN
108+
orders o ON u.id = o.user_id
109+
WHERE
110+
u.created_at >= '2024-01-01'
111+
AND u.status = 'active'
112+
GROUP BY
113+
u.id, u.username, u.email
114+
HAVING
115+
COUNT(o.id) > 5
116+
ORDER BY
117+
order_count DESC
118+
LIMIT 10;
119+
120+
121+

tools/fragment/data.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
name: 代码片段提取工具
2+
tags:
3+
- 代码片段提取工具
4+
title: 代码片段提取工具
5+
description: 代码片段提取工具

tools/fragment/logo.png

1.34 KB
Loading

0 commit comments

Comments
 (0)