import os import re def get_menu_html(current_page): return '''

地产后台管理

''' def update_file(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 获取当前页面名称 current_page = os.path.basename(file_path) # 替换菜单部分 menu_pattern = r'.*?\s*' menu_html = get_menu_html(current_page) # 在新的菜单HTML中,将当前页面的链接样式改为激活状态 current_link_pattern = f'href="{current_page}" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 rounded"' active_link = f'href="{current_page}" class="flex items-center px-4 py-2 text-blue-300 bg-blue-600 rounded"' menu_html = menu_html.replace(current_link_pattern, active_link) # 使用正则表达式替换菜单部分 new_content = re.sub(menu_pattern, menu_html.strip(), content, flags=re.DOTALL) # 更新文件 with open(file_path, 'w', encoding='utf-8') as f: f.write(new_content) def main(): # 获取当前目录下的所有HTML文件 html_files = [f for f in os.listdir('.') if f.endswith('.html')] # 更新每个文件的菜单 for file_name in html_files: print(f'正在更新: {file_name}') update_file(file_name) print(f'已完成: {file_name}') if __name__ == '__main__': main()