Below is a self-contained Python 3 script that
- Scans
D:\Progr\Auto for every file ending in .htm
- Strips the HTML tags and tokenises the visible text
- Builds n-grams of a fixed size
N (hard-coded – change the constant if you wish)
- Counts their occurrences across all files
- Creates (or overwrites)
ngrams.db and writes every n-gram whose frequency is > 5 into table ngrams(ngram TEXT, count INTEGER)
#!/usr/bin/env python3
"""
ngram_extractor.py
Extract N-grams from every .htm file in a directory and store the results
(count > 5) in an SQLite database (ngrams.db).
Author: <your-name>
"""
import os
import re
import sqlite3
from collections import Counter
from pathlib import Path
from html import unescape
# ────────────────────────── USER SETTINGS ────────────────────────── #
DIRECTORY = Path(r"D:\Progr\Auto") # Folder that holds the .htm files
DB_PATH = Path("ngrams.db") # New database will be created/overwritten
N = 3 # <<── the n in N-gram (hard-code here)
FREQ_MIN = 5 # Only keep n-grams occurring > this value
# ──────────────────────────────────────────────────────────────────── #
TAG_RE = re.compile(r"<[^>]+>") # crude HTML tag stripper
TOKEN_RE = re.compile(r"[A-Za-zА-Яа-я0-9]+", re.UNICODE) # keep letters & digits
def html_to_text(html: str) -> str:
"""Very small helper: strip tags & unescape entities."""
return unescape(TAG_RE.sub(" ", html))
def tokenize(text: str):
"""Return a list of lowercase tokens: 'Hello, world!' -> ['hello', 'world']"""
return [m.group(0).lower() for m in TOKEN_RE.finditer(text)]
def ngrams(tokens, n: int):
"""Yield n-gram tuples from a list/sequence of tokens."""
return zip(*(tokens[i:] for i in range(n)))
def collect_ngrams(folder: Path, ext: str = ".htm") -> Counter:
"""Walk the folder and count n-grams in every matching file."""
counts = Counter()
for file in folder.rglob(f"*{ext}"):
try:
with file.open("r", encoding="utf-8", errors="ignore") as fh:
raw_html = fh.read()
except (OSError, UnicodeError) as e:
print(f"[WARN] Skipping {file}: {e}")
continue
text = html_to_text(raw_html)
tokens = tokenize(text)
# Update counter with n-grams from this file
counts.update(ngrams(tokens, N))
return counts
def save_to_sqlite(ngrams_counter: Counter, db_path: Path):
"""Create table `ngrams` and insert (ngram, count) rows."""
if db_path.exists():
db_path.unlink() # start fresh each run (remove if you want append)
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("""
CREATE TABLE ngrams (
ngram TEXT PRIMARY KEY,
count INTEGER NOT NULL
)
""")
# Prepare bulk insert
rows = [(" ".join(ngram), cnt) for ngram, cnt in ngrams_counter.items() if cnt > FREQ_MIN]
cur.executemany("INSERT INTO ngrams (ngram, count) VALUES (?, ?)", rows)
conn.commit()
conn.close()
print(f"[OK] Stored {len(rows)} n-grams in {db_path}")
# ────────────────────────────── main ─────────────────────────────── #
if __name__ == "__main__":
if not DIRECTORY.exists():
raise SystemExit(f"Folder {DIRECTORY} not found!")
print(f"Scanning {DIRECTORY} for *.htm (N={N}) ...")
counter = collect_ngrams(DIRECTORY)
print(f"Total unique n-grams found: {len(counter)}")
save_to_sqlite(counter, DB_PATH)
How to run
python ngram_extractor.py
Feel free to tweak:
• N to change the gram size
• FREQ_MIN to adjust the “> 5” threshold
• TOKEN_RE if you need a different tokenisation rule
• Remove the db_path.unlink() line if you want to accumulate results across runs instead of recreating the DB every time.