当我们下载好看的html模板文件,通常包含静态资源路径,但一个个地去改成django用的模板引用static目录的资源,实在太麻烦,不知道vscode ide里有没有已有的插件可以直换替换路径。。。
由于时间关系,已经写好了,代码如下:
import re
def replace_static_paths(html_content):
# 正则表达式匹配常见的静态资源路径
patterns = [
r'(href|src)=["\']([^"\']+\.(css|js|png|jpg|jpeg|gif|svg))["\']',
]
# 替换函数
def replace_match(match):
attr = match.group(1) # 获取属性名(href或src)
path = match.group(2) # 获取路径
return f'{attr}="{{% static \'{path}\' %}}"'
# 遍历所有模式并进行替换
for pattern in patterns:
html_content = re.sub(pattern, replace_match, html_content)
return html_content
def process_template(input_file, output_file):
# 读取输入文件内容
with open(input_file, 'r', encoding='utf-8') as file:
html_content = file.read()
# 处理HTML内容
processed_html = replace_static_paths(html_content)
# 在文件开头添加 {% load static %}
processed_html = "{% load static %}\n" + processed_html
# 将处理后的内容写入输出文件
with open(output_file, 'w', encoding='utf-8') as file:
file.write(processed_html)
print(f"处理完成!已生成新文件: {output_file}")
# 示例:输入文件和输出文件路径
a=input('请输入文件名:')
input_file = a +'.html' # 输入的HTML文件路径
output_file = a + '.html' # 输出的HTML文件路径
# 处理模板文件
process_template(input_file, output_file)
也可以生成exe,用命令pyinstaller --onefile xxx.py生成exe文件,直接拖入html文件在exe文件上运行,自动生成处理后的html文件在当前目录,代码如下:
import re
import sys
import os
def replace_static_paths(html_content):
# 正则表达式匹配常见的静态资源路径
patterns = [
r'(href|src)=["\']([^"\']+\.(css|js|png|jpg|jpeg|gif|svg))["\']',
]
# 替换函数
def replace_match(match):
attr = match.group(1) # 获取属性名(href或src)
path = match.group(2) # 获取路径
return f'{attr}="{{% static \'{path}\' %}}"'
# 遍历所有模式并进行替换
for pattern in patterns:
html_content = re.sub(pattern, replace_match, html_content)
return html_content
def process_template(input_file):
# 读取输入文件内容
with open(input_file, 'r', encoding='utf-8') as file:
html_content = file.read()
# 处理HTML内容
processed_html = replace_static_paths(html_content)
# 在文件开头添加 {% load static %}
processed_html = "{% load static %}\n" + processed_html
# 生成输出文件名
output_file = os.path.splitext(input_file)[0] + "_processed.html"
# 将处理后的内容写入输出文件
with open(output_file, 'w', encoding='utf-8') as file:
file.write(processed_html)
print(f"处理完成!已生成新文件: {output_file}")
if __name__ == "__main__":
# 检查是否有拖放的文件
if len(sys.argv) > 1:
input_file = sys.argv[1] # 获取拖放的文件路径
if os.path.isfile(input_file) and input_file.lower().endswith('.html'):
process_template(input_file)
else:
print("错误:请拖放一个有效的HTML文件!")
else:
print("请将HTML文件拖放到此程序上!")