Here's a Python script that reads HTML files, extracts bigrams, and stores them in an SQLite database:
import os
import sqlite3
import re
from collections import Counter
def extract_text_from_html(file_path):
"""Extract text content from HTML file."""
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
content = file.read()
# Remove HTML tags
text = re.sub(r'<[^>]+>', ' ', content)
# Remove extra whitespace
text = ' '.join(text.split())
return text
def extract_bigrams(text):
"""Extract bigrams from text."""
# Convert to lowercase and keep only alphanumeric characters
words = re.findall(r'\b[a-zA-Z0-9]+\b', text.lower())
# Create bigrams
bigrams = []
for i in range(len(words) - 1):
bigram = f"{words[i]} {words[i+1]}"
bigrams.append(bigram)
return bigrams
def main():
# Directory containing HTML files
directory = r"D:\Progr\Auto"
# Database connection
conn = sqlite3.connect('bigrams.db')
cursor = conn.cursor()
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS bigrams (
bigram TEXT PRIMARY KEY,
count INTEGER
)
''')
# Clear existing data (optional - remove if you want to append)
cursor.execute('DELETE FROM bigrams')
# Counter for all bigrams
all_bigrams = Counter()
# Process all .htm files in the directory
for filename in os.listdir(directory):
if filename.endswith('.htm'):
file_path = os.path.join(directory, filename)
print(f"Processing: {filename}")
try:
# Extract text from HTML
text = extract_text_from_html(file_path)
# Extract bigrams
bigrams = extract_bigrams(text)
# Update counter
all_bigrams.update(bigrams)
except Exception as e:
print(f"Error processing {filename}: {e}")
# Insert bigrams with count > 10 into database
inserted_count = 0
for bigram, count in all_bigrams.items():
if count > 10:
cursor.execute('''
INSERT OR REPLACE INTO bigrams (bigram, count)
VALUES (?, ?)
''', (bigram, count))
inserted_count += 1
# Commit changes and close connection
conn.commit()
conn.close()
print(f"\nProcessing complete!")
print(f"Total unique bigrams found: {len(all_bigrams)}")
print(f"Bigrams with count > 10 inserted: {inserted_count}")
if __name__ == "__main__":
main()
This script does the following:
-
Reads HTML files: It scans the specified directory for all files with the .htm extension.
-
Extracts text: It removes HTML tags from the content using regular expressions to get clean text.
-
Creates bigrams: It tokenizes the text into words (alphanumeric only) and creates bigrams (consecutive word pairs).
-
Counts occurrences: It uses Python's Counter class to efficiently count all bigram occurrences across all files.
-
Database operations:
- Creates the
bigrams table if it doesn't exist
- Clears existing data (you can comment out this line if you want to append)
- Inserts only bigrams with count > 10
-
Error handling: Includes try-except blocks to handle potential file reading errors.
The script will create the database file bigrams.db in the same directory where you run the script. Make sure you have write permissions in that directory.
To run the script, save it as a .py file and execute it with Python. The script will print progress information and a summary at the end.