import re
def readTxt(txtPath):
titleList = []
pList = []
num = 0
with open('边城.txt', 'r', encoding='utf-8') as f:
txt = f.read()
ts = txt.split('\n\n')
for t in ts:
for p in t.split('\n'):
if p:
if p[0] != ' ':
# print(p[0])
titleList.append(p)
pList.append(t)
pList[num] = pList[num].replace('\n' + titleList[num] + '\n', '').replace(titleList[num] + '\n', '')
num += 1
return [titleList, pList]
# 写入htm文件
def writeHtm(titleList, pList):
# 生成文章链接 也是文件名
herfs = []
for i in range(len(titleList)):
herf = 'biancheng%03d.htm' % i
herfs.append(herf)
with open('模板.htm', 'r', encoding='utf-8') as f:
htm = f.read()
# print(htm)
"""
=0 [GOPREV]=>'' [GOINDEX]=>首页 [GONEXT]=> 下一页 [PART1]=> 标题 [PART0]=> 文章 [PAGETYPE]=> type
=1 [GOPREV]=>'上一页' [GOINDEX]=>首页 [GONEXT]=> 下一页 [PART1]=> 标题 [PART0]=> 文章 [PAGETYPE]=> type
=2 [GOPREV]=>'上一页' [GOINDEX]=> 首页 [GONEXT]=> 下一页 [PART1]=> 标题 [PART0]=> 文章 [PAGETYPE]=> type
=21 [GOPREV]=>'上一页' [GOINDEX]=> 首页 [GONEXT]=> 下一页 [PART1]=> 标题 [PART0]=> 文章 [PAGETYPE]=> type
=22 [GOPREV]=>'上一页' [GOINDEX]=> 首页 [GONEXT]=> '' [PART1]=> 标题 [PART0]=> 文章 [PAGETYPE]=> type
"""
for i in range(len(titleList)):
title = titleList[i]
p = pList[i].replace(' ', '')
if i == 0:
nextHerf = herfs[i + 1]
newHtm = htm.replace('[GOPREV]', '').replace('[GOINDEX]', '首页').replace('[GONEXT]', '下一页' % nextHerf).replace('[PART1]', title).replace('[PART0]', p).replace('[PAGETYPE]', 'type')
newHtm1 = re.sub(r'
(.*?)', '%s' % titleList[i], newHtm)with open(herfs[i], 'a+', encoding="utf-8") as f:
f.write(newHtm1)
if i > 0 and i < len(titleList)-1:
prevHerf = herfs[i - 1]
nextHerf = herfs[i + 1]
newHtm = htm.replace('[GOPREV]', '上一页' % prevHerf).replace('[GOINDEX]', '首页').replace('[GONEXT]', '下一页' % nextHerf).replace('[PART1]', title).replace('[PART0]',p).replace('[PAGETYPE]', 'type')
newHtm1 = re.sub(r'
(.*?)', '%s' % titleList[i], newHtm)with open(herfs[i], 'a+', encoding="utf-8") as f:
f.write(newHtm1)
if i == len(titleList)-1:
prevHerf = herfs[i - 1]
newHtm = htm.replace('[GOPREV]', '上一页' % prevHerf).replace('[GOINDEX]','首页').replace('[GONEXT]', '').replace('[PART1]', title).replace('[PART0]',p).replace('[PAGETYPE]', 'type')
newHtm1 = re.sub(r'
(.*?)', '%s' % titleList[i], newHtm)with open(herfs[i], 'a+', encoding="utf-8") as f:
f.write(newHtm1)
def indexHtm(titleList):
# 写入index.htm
# 生成文章链接
mulus = []
for i in range(len(titleList)):
mulu = '%s
' % (i, titleList[i])
mulus.append(mulu)
muluStr = ''.join(mulus)
with open('index模板.htm', 'r') as f:
index = f.read()
newIndex = index.replace('[shuming]', '边城').replace('[mulus]', muluStr).replace(r'
(.*?)', '#####')newIndex2 = re.sub(r'
(.*?)', '边城',newIndex)with open('index.htm', 'a+', encoding='gbk') as f:
f.write(newIndex2)
if __name__ == '__main__':
# 读取小说
[titleList, pList] = readTxt('边城.txt')
# 写入文章htm文件
writeHtm(titleList, pList)
# 写入index.htm文件
indexHtm(titleList)