Skip to content

Instantly share code, notes, and snippets.

@maaduukaar
Created June 30, 2025 11:56
Show Gist options
  • Save maaduukaar/58629990c936e092dfc346ac023511ba to your computer and use it in GitHub Desktop.
Save maaduukaar/58629990c936e092dfc346ac023511ba to your computer and use it in GitHub Desktop.
import os
import re
def replace_in_html_files(pattern, replacement, folder_path):
# Компилируем регулярное выражение
regex = re.compile(pattern, re.DOTALL | re.IGNORECASE)
# Счетчики для статистики
total_files = 0
processed_files = 0
files_with_matches = 0
files_without_matches = 0
print("Начинаю обработку HTML файлов...")
print("-" * 50)
# Проходим по всем файлам в папке
for filename in os.listdir(folder_path):
if filename.endswith('.html'):
total_files += 1
file_path = os.path.join(folder_path, filename)
print(f"Обрабатываю файл: {filename}")
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Проверяем, найден ли паттерн
matches = regex.findall(content)
if matches:
# Заменяем блок кода по регулярному выражению
new_content = regex.sub(replacement, content)
# Записываем изменения обратно в файл
with open(file_path, 'w', encoding='utf-8') as file:
file.write(new_content)
files_with_matches += 1
print(f" ✓ Найдено и заменено совпадений: {len(matches)}")
else:
files_without_matches += 1
print(f" - Паттерн не найден")
processed_files += 1
except Exception as e:
print(f" ✗ Ошибка при обработке: {e}")
# Выводим итоговую статистику
print("-" * 50)
print("СТАТИСТИКА ОБРАБОТКИ:")
print(f"Всего HTML файлов найдено: {total_files}")
print(f"Успешно обработано файлов: {processed_files}")
print(f"Файлов с найденным паттерном: {files_with_matches}")
print(f"Файлов без паттерна: {files_without_matches}")
if processed_files > 0:
success_rate = (files_with_matches / processed_files) * 100
print(f"Процент успешных замен: {success_rate:.1f}%")
# Пример использования
pattern = r"<!--footer-->.*?<!-- //Rating Mail\.ru counter -->"
replacement = """<!-- Плейсхолдер футера. Начало -->
<div id="footer-placeholder"></div>
<script>
async function loadFooter() {
const res = await fetch('/includes/footer.html');
const html = await res.text();
const container = document.getElementById('footer-placeholder');
const temp = document.createElement('div');
temp.innerHTML = html;
// Вставляем всё, кроме скриптов
const scripts = temp.querySelectorAll('script');
scripts.forEach(s => s.remove());
container.innerHTML = temp.innerHTML;
// Запускаем скрипты вручную
// Это нужно, чтобы избежать проблем с загрузкой скриптов, которые есть в футере
// В частности для формы Dashamail
scripts.forEach(oldScript => {
const newScript = document.createElement('script');
for (let attr of oldScript.attributes) {
newScript.setAttribute(attr.name, attr.value);
}
newScript.textContent = oldScript.textContent;
document.body.appendChild(newScript);
});
}
loadFooter();
</script>
<!-- Плейсхолдер футера. Конец -->"""
replace_in_html_files(pattern, replacement, '.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment