Write the script in Python that reads all the files "htm" in the directory "D:\Progr\Auto", extracts the trigrams from them and writes the unique trigrams and their count (if exceeds 5) to the respective cells "trigram" and "count" of the table "trigrams" in the newly created SQLite database "trigrams.db".
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
BeautifulSoup: You need to install the BeautifulSoup library, which is excellent for parsing HTML. Open your command prompt or terminal and run:
bash
pip install beautifulsoup4
Python Script:
python
import os
import sqlite3
import re
from collections import Counter
from bs4 import BeautifulSoup
# --- Configuration ---
SOURCE_DIR = r"D:\Progr\Auto" # Directory containing the .htm files (use raw string for Windows paths)
DB_FILE = "trigrams.db" # Name of the SQLite database file
TABLE_NAME = "trigrams" # Name of the table within the database
MIN_TRIGRAM_COUNT = 5 # Minimum count for a trigram to be saved
def setup_database(db_path, table_name):
"""Connects to the SQLite database and creates the table if it doesn't exist."""
conn = None
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create table with a UNIQUE constraint on trigram to avoid duplicates easily
cursor.execute(f'''
CREATE TABLE IF NOT EXISTS {table_name} (
trigram TEXT UNIQUE,
count INTEGER
)
''')
conn.commit()
print(f"Database '{db_path}' setup complete. Table '{table_name}' is ready.")
return conn, cursor
except sqlite3.Error as e:
print(f"Database error during setup: {e}")
if conn:
conn.close()
return None, None
except Exception as e:
print(f"An unexpected error occurred during database setup: {e}")
if conn:
conn.close()
return None, None
def extract_trigrams_from_html(html_content):
"""Extracts words from HTML content and generates trigrams."""
trigrams = []
try:
# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
# Extract text, using space as separator for better word separation
# Remove script and style elements first
for script_or_style in soup(["script", "style"]):
script_or_style.decompose() # Remove these elements entirely
text = soup.get_text(separator=' ', strip=True)
# Use regex to find sequences of word characters (\w includes letters, numbers, underscore)
# \b ensures we match whole words
words = re.findall(r'\b\w+\b', text.lower()) # Convert to lowercase
# Generate trigrams if we have enough words
if len(words) >= 3:
for i in range(len(words) - 2):
trigram = " ".join(words[i:i+3])
trigrams.append(trigram)
except Exception as e:
# Catch potential errors during parsing or regex matching
print(f" Error extracting trigrams: {e}")
return trigrams
def process_files_and_populate_db(source_dir, conn, cursor, table_name, min_count):
"""
Reads HTML files, counts trigrams, and inserts frequent ones into the database.
"""
if not os.path.isdir(source_dir):
print(f"Error: Source directory '{source_dir}' not found.")
return 0
all_trigrams_counter = Counter()
files_processed = 0
total_trigrams_found = 0
print(f"\nScanning directory: {source_dir}")
# Iterate through all files in the source directory
for filename in os.listdir(source_dir):
# Process only files ending with .htm or .html (case-insensitive)
if filename.lower().endswith((".htm", ".html")):
filepath = os.path.join(source_dir, filename)
print(f"Processing file: {filepath}...")
try:
# Open and read the HTML file content
# Use utf-8 encoding and ignore errors for robustness
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
html_content = f.read()
# Extract trigrams from the current file's content
current_file_trigrams = extract_trigrams_from_html(html_content)
if current_file_trigrams:
# Update the global counter with trigrams from this file
all_trigrams_counter.update(current_file_trigrams)
total_trigrams_found += len(current_file_trigrams)
files_processed += 1
except FileNotFoundError:
print(f" Warning: File not found during read: {filepath}")
except IOError as e:
print(f" Error reading file {filepath}: {e}")
except Exception as e:
print(f" An unexpected error occurred processing file {filepath}: {e}")
print(f"\nFinished processing files. Processed {files_processed} files.")
print(f"Found a total of {total_trigrams_found} trigrams across all files.")
print(f"Total unique trigrams found: {len(all_trigrams_counter)}")
# --- Database Insertion ---
insert_count = 0
print(f"\nInserting trigrams with count > {min_count} into '{DB_FILE}'...")
# Prepare the SQL statement for insertion, using INSERT OR IGNORE due to UNIQUE constraint
sql_insert = f"INSERT OR IGNORE INTO {table_name} (trigram, count) VALUES (?, ?)"
# Iterate through the counted trigrams
for trigram, count in all_trigrams_counter.items():
if count > min_count:
try:
cursor.execute(sql_insert, (trigram, count))
# Check if the insertion actually happened (cursor.rowcount is 1 if inserted, 0 if ignored)
if cursor.rowcount > 0:
insert_count += 1
except sqlite3.Error as e:
print(f" Error inserting trigram '{trigram}': {e}")
except Exception as e:
print(f" An unexpected error occurred inserting trigram '{trigram}': {e}")
# Commit the changes to the database
try:
conn.commit()
print(f"\nSuccessfully inserted {insert_count} unique trigrams into the database.")
except sqlite3.Error as e:
print(f"Database error during commit: {e}")
return insert_count
# --- Main Execution ---
if __name__ == "__main__":
print("Starting trigram extraction script...")
# Setup database connection and table
connection, db_cursor = setup_database(DB_FILE, TABLE_NAME)
if connection and db_cursor:
# Process files and populate the database
process_files_and_populate_db(SOURCE_DIR, connection, db_cursor, TABLE_NAME, MIN_TRIGRAM_COUNT)
# Close the database connection
connection.close()
print("Database connection closed.")
else:
print("Failed to initialize database. Exiting.")
print("\nScript finished.")
Explanation:
Import Libraries: Imports necessary modules (os for file system, sqlite3 for database, re for regular expressions, collections.Counter for counting, bs4.BeautifulSoup for HTML parsing).
Configuration: Sets the source directory, database file name, table name, and the minimum count threshold. Remember to change SOURCE_DIR if your directory path is different.
setup_database Function:
Connects to the specified SQLite database file (creates it if it doesn't exist).
Creates the trigrams table with two columns: trigram (TEXT) and count (INTEGER).
Crucially, it adds a UNIQUE constraint to the trigram column. This prevents duplicate trigrams from being inserted later using INSERT OR IGNORE.
Includes error handling for database connection and table creation.
extract_trigrams_from_html Function:
Takes the raw HTML content as input.
Uses BeautifulSoup to parse the HTML.
Finds and removes <script> and <style> tags as they usually don't contain relevant textual content for trigrams.
Uses soup.get_text(separator=' ', strip=True) to extract only the visible text, replacing tag structures with spaces.
Uses re.findall(r'\b\w+\b', text.lower()) to find all sequences of alphanumeric characters (words), converting them to lowercase and ignoring punctuation.
Iterates through the list of words to create trigrams (sequences of three consecutive words).
Returns a list of trigrams found in the file. Includes basic error handling.
process_files_and_populate_db Function:
Initializes an empty Counter to store trigram counts globally across all files.
Checks if the source directory exists.
Iterates through each file in the SOURCE_DIR using os.listdir.
Checks if the filename ends with .htm or .html (case-insensitive).
Opens each matching file with UTF-8 encoding (common for web pages) and error handling (errors='ignore' prevents crashes on malformed characters).
Calls to get trigrams from the file's content.
This script provides a robust way to achieve your goal, including basic error handling and efficient processing.
Uses all_trigrams_counter.update() to efficiently add the trigrams and update their counts.
Includes try...except blocks to handle potential file reading errors.
After processing all files, it iterates through the all_trigrams_counter.items().
For each (trigram, count) pair, if count is greater than MIN_TRIGRAM_COUNT, it attempts to insert the pair into the database using INSERT OR IGNORE. This command will only insert the row if a trigram with the same text doesn't already exist in the table (thanks to the UNIQUE constraint).
Commits all the successful insertions to the database.
Prints summary information.
Main Execution Block (if __name__ == "__main__":)
This ensures the code runs only when the script is executed directly.
Calls setup_database to prepare the database.
If setup is successful, it calls process_files_and_populate_db to do the main work.