Python Script to Extract Fourgrams and Store in SQLite Database
Here's a Python script that:
- Reads all .htm files from the specified directory
- Extracts fourgrams (sequences of 4 consecutive words)
- Counts their occurrences
- Stores unique fourgrams with counts > 5 in an SQLite database
import os
import re
import sqlite3
from collections import defaultdict
def extract_fourgrams(text):
"""Extract fourgrams from text"""
# Remove HTML tags
clean_text = re.sub(r'<[^>]+>', ' ', text)
# Remove non-alphabetic characters and convert to lowercase
words = re.findall(r'\b[a-zA-Z]+\b', clean_text.lower())
# Generate fourgrams
fourgrams = [' '.join(words[i:i+4]) for i in range(len(words)-3)]
return fourgrams
def process_files(directory):
"""Process all .htm files in directory and return fourgram counts"""
fourgram_counts = defaultdict(int)
for filename in os.listdir(directory):
if filename.endswith('.htm'):
filepath = os.path.join(directory, filename)
try:
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
fourgrams = extract_fourgrams(content)
for fourgram in fourgrams:
fourgram_counts[fourgram] += 1
except Exception as e:
print(f"Error processing {filename}: {e}")
return fourgram_counts
def create_database(fourgram_counts, db_path='fourgrams.db'):
"""Create SQLite database and store fourgrams with count > 5"""
# Connect to SQLite database (creates if doesn't exist)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create table
cursor.execute('''
CREATE TABLE IF NOT EXISTS fourgrams (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fourgram TEXT UNIQUE,
count INTEGER
)
''')
# Insert fourgrams with count > 5
for fourgram, count in fourgram_counts.items():
if count > 5:
try:
cursor.execute('''
INSERT INTO fourgrams (fourgram, count)
VALUES (?, ?)
''', (fourgram, count))
except sqlite3.IntegrityError:
# Handle case where fourgram already exists (though our data should be unique)
pass
conn.commit()
conn.close()
def main():
directory = r'D:\Progr\Auto'
# Process files and get fourgram counts
print("Processing files and extracting fourgrams...")
fourgram_counts = process_files(directory)
# Create database and store results
print("Creating database and storing results...")
create_database(fourgram_counts)
print(f"Done! Results stored in fourgrams.db")
if __name__ == '__main__':
main()
How to Use This Script
- Save this script to a file (e.g.,
extract_fourgrams.py)
- Make sure you have Python installed
- Run the script:
python extract_fourgrams.py
Notes
- The script handles basic HTML cleaning by removing tags before processing
- It converts all text to lowercase for consistent counting
- Only alphabetic words are considered (numbers and punctuation are ignored)
- The database will be created in the same directory as the script
- The script skips any files it can't read and continues processing
- Fourgrams must appear more than 5 times to be stored in the database
You can modify the threshold (currently 5) by changing the condition in the create_database function.