- 待解决问题
- 实现效果
- 完整代码
(用“圆明园百科词条”举例说明)
??排好版的文本,一贴上博文,就纠结在一坨了。好难受😭😭
??其实,是有办法的,那就是上HTML标签,让博文按自己的意愿显现。 (
回页首)
??这样子,是不是好看多了。😁😁
??那么多标签,好难加。慢!有
妙方,那就是祭出python代码的
利剑,秒完成标签添加。😃😃(
回页首)
??上代码……
import glob, os, re
l = os.system(r'clear')
def to_html(filename):
with open(r'./%s'%filename) as f:
while True:
title_s = f.readline().strip().replace('\n', '')
if title_s!='':
break
txt_file = f.read()
txt_file = txt_file.replace(' ', ' '*2)
txt_file = txt_file.replace('\n', '<br>')
j40_s = re.findall(r'\d{1,2}[.][ ](\w{1,16})[:](?#正则表达注释:提取圆明园40景名字符)', txt_file)
print('\n圆明园40景列表:\n', j40_s)
input('\n 共找到欲加粗的%s处圆明园景点名称。\n'%len(j40_s))
k = 1
for i in j40_s:
print(r'%2d、“%s”替换为:'%(k, s := r'. %s'%i), re_s := r'. <b>%s</b>'%i)
txt_file = txt_file.replace(s, re_s)
k += 1
input('\n 圆明园景名称完成加粗%s处。\n'%len(j40_s))
b_s = re.findall(r'<br><br><br>(\w{1,16})(?#提取1~16个标题字符)', txt_file)
print('\n小标题列表:\n', b_s)
input('\n 共提取到欲加粗的%s处小标题。\n'%len(b_s))
k = 1
for i in b_s:
print(r'%2d、“%s”替换为:'%(k, s := r'<br><br><br>%s'%i), re_s := r'<br><p><b>%s</b>'%i)
txt_file = txt_file.replace(s, re_s)
k += 1
input('\n 共完成加粗小标题%s处。\n'%len(b_s))
img_s = re.findall(r'img(\w{1,30})(?#提取1~30个图片链接信息字符)', txt_file)
print('\n图片链接位置列表:\n', img_s)
input('\n 共找到图片链接%s处。\n'%len(img_s))
img_file = glob.glob(r'./Img/*.jpg')
k = 0
for i in img_s:
print(r'%2d、“%s”替换为:'%(k+1, s := r'img%s'%i), re_s := r"<center><img src='%s' alt='%s' title='%s' width='500px'></center>"%(img_file[k], i, i))
txt_file = txt_file.replace(s, re_s)
k += 1
input('\n 共完成图片链接标签代码添加%s处。\n'%len(img_s))
k = 2
filename = title_s
while True:
if glob.glob(r'./%s.html'%filename)!=[]:
flag = input(''.join(['\n'*2, ' '*12, '文件重名!覆盖?(Y/N)']))
if flag not in ('n', 'N'):
break
filename = title_s + str(k)
k += 1
else:
break
f2 = open(r'./%s.html'%filename, 'w')
head_s = r'''<html>
<head>
<style>
body{
font-size: %s;
width: 900;
height: auto;
margin: auto;
margin-bottom: 20px;
color: #003366;
background-color: #99CCFF;
border: 1px solid #AAAFAA;
}
</style>
<title>%s</title>
</head>'''%('150%', title_s)
f2.write(head_s)
f2.write(r'<body>')
f2.write(r'<center><h1>%s</h1></center>'%title_s)
f2.write(txt_file)
f2.write(r'</body>')
f2.write(r'</html>')
f2.close()
if __name__=='__main__':
print('')
for i in glob.glob('./*.txt'):
to_html(i)
print('\n新生成的HTML文件列表:\n')
os.system(r'ls -l ./*.html')
回页首
精品文章:
来源:老齐教室
|