-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
216 lines (187 loc) · 7.45 KB
/
build.py
File metadata and controls
216 lines (187 loc) · 7.45 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from cStringIO import StringIO
import re
from cgi import escape
PAGE_RE = re.compile(r"(page:)(.*?)([\s|\n])")
BLOD_RE = re.compile(r"(\[\[)(.*?)(\]\])")
#BLOD_RE.sub(r'<b>\2</b>', line)
romanNumeralMap = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1))
from urllib2 import unquote
import re
linkre = re.compile(r'((?:https?://)'
r'[\w\-.%/=+#:~!,\'\*\^]+'
r'(?:\?[\w\-.%/=;+@#:~!,\'\*&$]*)?)')
def escape_link(s):
s = str(s).decode('utf8', 'ignore').encode('utf8')
rs=[]
for tok in linkre.split(s):
if linkre.match(tok) and tok not in '"<>':
linktext = tok
if tok.startswith('http://') or tok.startswith('https://'):
href = tok
else:
href = 'http://' + tok
rs.append("""<a target="_blank" href="%s">%s</a>""" % (href,linktext))
else:
rs.append(tok)
return ''.join(rs)
def toRoman(n):
"""convert integer to Roman numeral"""
result = ""
for numeral, integer in romanNumeralMap:
while n >= integer:
result += numeral
n -= integer
return result
from os.path import dirname,join
PREFIX = dirname(__file__)
PREFIX_OUTPUT = join(PREFIX,"html")
from os import walk
from collections import defaultdict
from mako.lookup import TemplateLookup
lookup = TemplateLookup(
directories=join(PREFIX,'template'),
disable_unicode=True,
encoding_errors="ignore",
default_filters=['str', 'h'],
)
def render(template,*args,**kwds):
return lookup.get_template(template).render(*args,**kwds)
chapter_title_dict={}
chapter_content_dict=defaultdict(list)
for root, dirs, files in walk(join(PREFIX,"book")):
for file in files:
if not file.endswith(".txt"):
continue
path = join(root,file).replace("\\","/")
other,chapter, number = path.rsplit("/",2)
number = number[:-4]
if chapter.isdigit():
chapter = int(chapter)
with open(path) as pathfile:
pathfile_read = pathfile.read()
if number == "init":
title = pathfile_read.strip()
chapter_title_dict[chapter] = title
elif number.isdigit():
number = int(number)
chapter_content_dict[chapter].append( (number , pathfile_read.rstrip()) )
for k,v in list(chapter_content_dict.items()):
v = sorted(v,key=lambda x:int(x[0]))
v = [
i for n,i in v
]
chapter_content_dict[k]=v
chapter_list = chapter_title_dict.keys()
chapter_list.sort()
pre_link = None
next_link = None
for chapter in chapter_list:
pathfile_list = chapter_content_dict.get(chapter,[])
for filepos,pathfile_read in enumerate(pathfile_list):
if pathfile_read.strip():
filename = "%s_%s.html"%(chapter,filepos)
with open(join(PREFIX_OUTPUT,filename),"w") as index:
pos = pathfile_read.find("\n")
if pos==-1:
continue
content = pathfile_read[pos:].strip()
if content:
if filepos<len(pathfile_list)-1 and pathfile_list[filepos+1].count("\n"):
next_link = "%s_%s.html"%(chapter,1+filepos)
elif chapter!=chapter_list[-1]:
next_link = "%s_%s.html"%(chapter_list[chapter_list.index(chapter)+1],0)
else:
next_link = None
else:
continue
content = escape(content)
content = BLOD_RE.sub(r'<b>\2</b>', content)
content = PAGE_RE.sub(r'<a href="page/\2" target="_blank">链接</a> ',content)
buffer = []
s = StringIO()
s.write(content)
s.seek(0)
inpre = False
for line in s:
line=line.rstrip()
line_strip = line.strip()
#print line
if line.startswith("~~"):
line = line.lstrip('~ ')
buffer.append("""<p><a href="%s">%s</a></p>"""%(line,line))
elif line.startswith("===") and line.endswith("==="):
buffer.append("<h3>%s</h3>"%line.strip(" ="))
elif line.startswith("==") and line.endswith("=="):
buffer.append("<h2>%s</h2>"%line.strip(" ="))
elif line_strip == "{{{":
inpre=True
buffer.append("""<div class="content"><pre>""")
elif line_strip == "}}}":
inpre=False
buffer.append("""</pre></div>""")
elif line_strip == "==>":
buffer.append("""<blockquote>""")
elif line_strip == "<==":
buffer.append("""</blockquote>""")
elif line_strip.startswith("----"):
buffer.append("""<div style="border:0;border-bottom:1px #ccc dotted;margin:40px 0;"></div>""")
elif line[-4:] in (".jpg",".gif",".png"):
alt = ""
link = line.rsplit(" ",1)
if len(link)==2:
alt,link = link
elif len(link)==1:
link=link[0]
buffer.append("""<div class="imageblock">
<div class="content">
<img alt="%s" src="img/%s"/>
</div>
"""%(alt,link))
if alt:
buffer.append("""<div class="image-title">图:%s</div>"""%alt)
buffer.append("""</div>""")
elif line:
line = escape_link(line)
if inpre:
buffer.append(line)
else:
buffer.append("<p>%s</p>"%line)
elif inpre:
buffer.append("")
content = "\n".join(buffer)
index.write(
render(
"page.html",
title = pathfile_read.strip().split("\n")[0],
content=content,
pre_link = pre_link,
next_link = next_link
),
)
pre_link = filename
with open(join(PREFIX_OUTPUT,"index.html"),"w") as index:
index.write(
render(
"index.html",
chapter_list = chapter_list,
chapter_number=map(toRoman,chapter_list),
chapter_title_dict = chapter_title_dict,
chapter_content_dict = chapter_content_dict
),
)