File size: 737 Bytes
a916ede
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""Shared HTML → text for fetchers. Block tags become newlines; inline tags drop."""
from __future__ import annotations
import re
from html import unescape

_SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
_BLOCK_END = re.compile(
    r"(?i)</(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|<br\s*/?>"
)
_TAG = re.compile(r"<[^>]+>")


def html_to_text(html: str) -> str:
    if not html:
        return ""
    html = _SCRIPT.sub("", html)
    html = _BLOCK_END.sub("\n", html)
    html = _TAG.sub("", html)
    text = unescape(html).replace("\r\n", "\n").replace("\r", "\n")
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r" *\n *", "\n", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()