Python Script to Extract Sixgrams from HTML Files and Store in SQLite Database
Here's a Python script that will:
- Read all
.htm files from the specified directory
- Extract sixgrams (sequences of 6 words) from the text content
- Count occurrences of each sixgram
- Store unique sixgrams with counts > 5 in an SQLite database
import os
import re
import sqlite3
from collections import defaultdict
from bs4 import BeautifulSoup
def extract_text_from_html(file_path):
"""Extract text content from HTML file using BeautifulSoup"""
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
soup = BeautifulSoup(file, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get text and clean it
text = soup.get_text()
# Remove extra whitespace and newlines
text = re.sub(r'\s+', ' ', text).strip()
return text
def extract_sixgrams(text):
"""Extract sixgrams from text"""
# Tokenize into words (simple approach - split on whitespace)
words = re.findall(r'\b\w+\b', text.lower())
sixgrams = []
# Generate sixgrams
for i in range(len(words) - 5):
sixgram = ' '.join(words[i:i+6])
sixgrams.append(sixgram)
return sixgrams
def process_directory(directory):
"""Process all .htm files in the directory"""
sixgram_counts = defaultdict(int)
for filename in os.listdir(directory):
if filename.endswith('.htm'):
file_path = os.path.join(directory, filename)
try:
text = extract_text_from_html(file_path)
sixgrams = extract_sixgrams(text)
for sixgram in sixgrams:
sixgram_counts[sixgram] += 1
except Exception as e:
print(f"Error processing {filename}: {e}")
return sixgram_counts
def create_database(sixgram_counts, db_path='sixgrams.db'):
"""Create SQLite database and store sixgrams with count > 5"""
# Filter sixgrams with count > 5
filtered_sixgrams = {k: v for k, v in sixgram_counts.items() if v > 5}
# Connect to SQLite database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS sixgrams (
sixgram TEXT PRIMARY KEY,
count INTEGER
)
''')
# Insert sixgrams
for sixgram, count in filtered_sixgrams.items():
cursor.execute('''
INSERT OR REPLACE INTO sixgrams (sixgram, count)
VALUES (?, ?)
''', (sixgram, count))
# Commit changes and close connection
conn.commit()
conn.close()
print(f"Database created at {db_path} with {len(filtered_sixgrams)} sixgrams (count > 5)")
def main():
directory = r'D:\Progr\Auto'
db_path = 'sixgrams.db'
if not os.path.exists(directory):
print(f"Directory {directory} does not exist.")
return
print("Processing HTML files...")
sixgram_counts = process_directory(directory)
print("Creating database...")
create_database(sixgram_counts, db_path)
print("Done!")
if __name__ == '__main__':
main()
Requirements
To run this script, you'll need to install the following Python packages:
pip install beautifulsoup4
Notes
- The script uses BeautifulSoup to extract text from HTML files, which helps remove HTML tags and other non-text elements.
- The sixgram extraction is case-insensitive (all words are converted to lowercase).
- The script handles basic text cleaning but you might want to enhance the text processing based on your specific needs.
- The database will be created in the same directory where the script is run unless you specify a full path for
db_path.
- The script includes error handling for file processing but you might want to add more robust error handling for production use.
You can modify the script as needed, such as changing the minimum count threshold or adjusting the text processing logic.