Files
core/utils/extract_text.py
Untone e78e12eeee
Some checks failed
Deploy on push / deploy (push) Failing after 17s
circular-fix
2025-08-17 16:33:54 +03:00

53 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Модуль для обработки HTML-фрагментов
"""
import re
def extract_text(html_content: str | None) -> str:
"""
Извлекает текст из HTML с помощью регулярных выражений.
Args:
html_content (Optional[str]): HTML-строка для извлечения текста
Returns:
str: Извлеченный текст или пустая строка
"""
if not html_content:
return ""
# Удаляем HTML-теги
text = re.sub(r"<[^>]+>", " ", html_content)
# Декодируем HTML-сущности
text = re.sub(r"&[a-zA-Z]+;", " ", text)
# Убираем лишние пробелы
return re.sub(r"\s+", " ", text).strip()
def wrap_html_fragment(fragment: str) -> str:
"""
Оборачивает HTML-фрагмент в полный HTML-документ.
Args:
fragment (str): HTML-фрагмент
Returns:
str: Полный HTML-документ
"""
if "<!DOCTYPE html>" in fragment and "<html>" in fragment:
return fragment
return f"""<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{fragment}
</body>
</html>"""