-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoc.py
130 lines (119 loc) · 4.62 KB
/
toc.py
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
# -*- encoding: utf-8 -*-
# 生成markdown文件的目录
import os
import sys
import time
from pathlib import Path
headline = ["#", "##", "###", "####", "#####", "######"]
lines_in_file = []
def creat_directory_line(line, headline_mark, i):
"""生成目录列表中的某一项"""
if headline_mark == "#":
return '<a href=" ' + str(i) + '">' + line[2:-1] + "</a> \n"
elif headline_mark == "##":
#  为Markdown中的一种缩进,这里不直接用空格作为缩进是因为多个空格一起出现可能会生成代码块,引发歧义
return ' <a href="#' + str(i) + '">' + line[3:-1] + "</a> \n"
elif headline_mark == "###":
return '  <a href="#' + str(i) + '">' + line[4:-1] + "</a> \n"
elif headline_mark == "####":
return '   <a href="#' + str(i) + '">' + line[5:-1] + "</a> \n"
elif headline_mark == "#####":
return (
'    <a href=" ' + str(i) + '">' + line[6:-1] + "</a> \n"
)
elif headline_mark == "######":
return (
'     <a href="#'
+ str(i)
+ '">'
+ line[7:-1]
+ "</a> \n"
)
def creat_directory(f):
"""生成目录列表"""
i = 0
directory = []
directory.append('<a name="index">**Index**</a>\n\n')
for line in f:
lines_in_file.append(line)
f.close()
length = len(lines_in_file)
code_status_cnt = 0
for j in range(length):
splitedline = lines_in_file[j].lstrip().split(" ")
if splitedline[0].strip()[:3] == "```":
code_status_cnt += 1
if splitedline[0] in headline and not (code_status_cnt % 2): # 确保该行不处于代码环境中
# 如果为最后一行且末尾无换行(防最后一个字被去除)
if j == length - 1 and lines_in_file[j][-1] != "\n":
directory.append(
creat_directory_line(lines_in_file[j] + "\n", splitedline[0], i)
+ "\n"
)
lines_in_file[j] = (
lines_in_file[j].replace(
splitedline[0] + " ",
splitedline[0] + " " + '<a name="' + str(i) + '">',
)[:]
+ '</a><a style="float:right;text-decoration:none;" href=" ">[Top]</a>'
+ "\n"
)
i = i + 1
else:
directory.append(
creat_directory_line(lines_in_file[j], splitedline[0], i)
)
lines_in_file[j] = (
lines_in_file[j].replace(
splitedline[0] + " ",
splitedline[0] + " " + '<a name="' + str(i) + '">',
)[:-1]
+ '</a><a style="float:right;text-decoration:none;" href="#index">[Top]</a>'
+ "\n"
)
i = i + 1
return directory
def creat_file_with_toc(f):
"""以目录列表为参数生成添加目录的文件"""
directory = creat_directory(f)
file_with_toc = Path(".") / "file_with_toc.md"
if not os.path.exists(file_with_toc):
with open(file_with_toc, "w+", encoding="utf-8") as f:
for directory_line in directory:
f.write(directory_line)
for line in lines_in_file:
f.write(line)
print("文件已生成:", file_with_toc.absolute().as_posix())
else:
print("文件名重复,请修改文件" + "file_with_toc.md" + "的文件名后重试")
if __name__ == "__main__":
file_name = ""
# 如果未传入文件名
if len(sys.argv) < 2:
path = os.getcwd()
file_and_dir = os.listdir(path)
md_file = []
for item in file_and_dir:
if item.split(".")[-1].lower() in [
"md",
"mdown",
"markdown",
] and os.path.isfile(item):
md_file.append(item)
if len(md_file) != 0:
print("当前目录下的Markdown文件:")
for file in md_file:
print(file)
file_name = input("请输入文件名(含后缀)\n")
else:
print("该目录下无Markdown文件,即将退出...")
time.sleep(2)
os._exit(0)
else:
file_name = sys.argv[1]
if os.path.exists(file_name) and os.path.isfile(file_name):
with open(file_name, "r", encoding="utf-8") as f:
creat_file_with_toc(f)
else:
msg = "未找到文件"
print(msg)