import os
import sqlite3
from collections import Counter
from bs4 import BeautifulSoup
import re
import sys
# --- Configuration ---
SOURCE_DIR = r'D:\Progr\Auto' # Use a raw string or double backslashes for Windows paths
DATABASE_PATH = 'sixgrams.db'
TABLE_NAME = 'sixgrams'
MIN_COUNT = 5 # Threshold for count
# --- Helper Function to Extract Text from HTML ---
def extract_text_from_html(filepath):
"""Reads an HTML file, extracts the text content using BeautifulSoup."""
try:
# Attempt to open with utf-8, fall back to latin-1 if needed
with open(filepath, 'r', encoding='utf-8') as f:
html_content = f.read()
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='latin-1') as f:
html_content = f.read()
except Exception as e:
print(f"Error reading {filepath}: {e}", file=sys.stderr)
return None
except FileNotFoundError:
print(f"Error: File not found at {filepath}", file=sys.stderr)
return None
except Exception as e:
print(f"An unexpected error occurred reading {filepath}: {e}", file=sys.stderr)
return None
try:
soup = BeautifulSoup(html_content, 'html.parser')
# Get text, remove script and style tags before getting text
for script_or_style in soup(["script", "style"]):
script_or_style.extract()
text = soup.get_text()
return text
except Exception as e:
print(f"Error parsing HTML from {filepath}: {e}", file=sys.stderr)
return None
# --- Helper Function to Clean Text and Get Words ---
def clean_and_split_text(text):
"""Cleans text (lowercase, remove punctuation) and splits into words."""
if text is None:
return []
# Convert to lowercase
text = text.lower()
# Split by non-alphanumeric characters (keeping spaces initially might be complex)
# A simple way is to replace non-word characters with spaces and then split by spaces
# Or, split directly by sequences of non-word characters
words = re.split(r'\W+', text) # Split by one or more non-alphanumeric characters
# Filter out empty strings that might result from the split
words = [word for word in words if word]
return words
# --- Main Script ---
if __name__ == "__main__":
# Check if the source directory exists
if not os.path.isdir(SOURCE_DIR):
print(f"Error: Source directory not found at {SOURCE_DIR}", file=sys.stderr)
sys.exit(1)
print(f"Starting sixgram extraction from {SOURCE_DIR}...")
all_sixgram_counts = Counter()
processed_files_count = 0
skipped_files_count = 0
# Walk through the directory to find HTML files
for root, _, files in os.walk(SOURCE_DIR):
for file in files:
if file.endswith('.htm'):
filepath = os.path.join(root, file)
print(f"Processing {filepath}...")
# Extract text
text = extract_text_from_html(filepath)
if text is None:
skipped_files_count += 1
continue # Skip this file
# Clean and split into words
words = clean_and_split_text(text)
# Generate sixgrams
if len(words) >= 6:
for i in range(len(words) - 5): # Iterate up to the point where a sixgram can be formed
sixgram = " ".join(words[i:i+6])
all_sixgram_counts[sixgram] += 1
processed_files_count += 1
else:
# File has less than 6 words, no sixgrams possible
processed_files_count += 1 # Still count as processed if text extraction worked
# print(f"Skipping sixgram generation for {file} (too few words).")
print("-" * 20)
print(f"Finished processing files.")
print(f"Processed {processed_files_count} HTML files.")
if skipped_files_count:
print(f"Skipped {skipped_files_count} files due to errors.")
print(f"Found a total of {len(all_sixgram_counts)} unique sixgrams.")
# Filter sixgrams with count > MIN_COUNT
filtered_sixgrams = [(sixgram, count) for sixgram, count in all_sixgram_counts.items() if count > MIN_COUNT]
print(f"Found {len(filtered_sixgrams)} unique sixgrams with a count exceeding {MIN_COUNT}.")
# --- Store results in SQLite database ---
print(f"Storing results in SQLite database: {DATABASE_PATH}")
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
# Drop the table if it exists to ensure a clean slate for the "newly created" requirement
cursor.execute(f"DROP TABLE IF EXISTS {TABLE_NAME}")
# Create the table
cursor.execute(f'''
CREATE TABLE {TABLE_NAME} (
sixgram TEXT UNIQUE, -- Each unique sixgram will have one row
count INTEGER
)
''')
# Insert the filtered data
if filtered_sixgrams:
cursor.executemany(f'''
INSERT INTO {TABLE_NAME} (sixgram, count)
VALUES (?, ?)
''', filtered_sixgrams)
print(f"Successfully inserted {len(filtered_sixgrams)} rows into '{TABLE_NAME}'.")
else:
print("No sixgrams met the minimum count threshold for insertion.")
# Commit the transaction
conn.commit()
print("Database transaction committed.")
except sqlite3.Error as e:
print(f"SQLite error: {e}", file=sys.stderr)
if conn:
conn.rollback() # Roll back changes if something went wrong
print("Database transaction rolled back.", file=sys.stderr)
finally:
# Close the connection
if conn:
conn.close()
print("Database connection closed.")
print("Script finished.")
Explanation:
- Import Libraries: Imports
os for file system operations, sqlite3 for database interaction, collections.Counter for efficient counting, BeautifulSoup for parsing HTML, re for text cleaning, and sys for error output.
- Configuration: Defines the
SOURCE_DIR, DATABASE_PATH, TABLE_NAME, and MIN_COUNT threshold. r'D:\Progr\Auto' uses a raw string to handle the backslashes correctly.
extract_text_from_html(filepath):
- Takes a file path as input.
- Uses
open() with encoding='utf-8'. Includes a try...except UnicodeDecodeError block to fall back to latin-1, which is common for older HTML files. Handles other potential file reading errors.
- If reading is successful, it creates a
BeautifulSoup object.
- It explicitly finds and removes
<script> and <style> tags using extract() before getting the text, as their content is usually not part of the visible text flow for sixgram analysis.
soup.get_text() extracts all text content from the HTML document, ignoring the tags themselves.
- Returns the extracted text or
None if an error occurred.
clean_and_split_text(text):
- Takes the raw text string.
- Converts the entire text to lowercase using
.lower().
- Uses
re.split(r'\W+', text) to split the text into words. \W+ matches one or more characters that are not word characters (alphanumeric plus underscore). This effectively splits by spaces, punctuation, newlines, etc.
- Filters out any empty strings that might have resulted from the split (e.g., if there were multiple non-word characters together).
- Returns a list of clean words.
- Main Execution Block (
if __name__ == "__main__":)
- Checks if the
SOURCE_DIR exists and exits if not.
- Initializes an empty
collections.Counter called all_sixgram_counts to store the counts of all unique sixgrams found across all files.
- Initializes counters for processed and skipped files.
- Uses to traverse the directory tree rooted at .