Write the script in Python that reads all the files "htm" in the directory "D:\Progr\Auto", extracts the fourgrams from them and writes the unique fourgrams and their count (if exceeds 5) to the respective cells "fourgram" and "count" of the table "fourgrams" in the newly created SQLite database "fourgrams.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.
import os
import sqlite3
from bs4 import BeautifulSoup
from collections import Counter
import re
# --- Configuration ---
source_directory = r"D:\Progr\Auto" # Use a raw string for the path to handle backslashes
database_path = "fourgrams.db"
table_name = "fourgrams"
min_count_threshold = 5 # We need to store if count exceeds 5 (i.e., count >= 6)
# --- Data Structure to hold all fourgrams and their counts ---
all_fourgrams_counter = Counter()
# --- Function to extract text from HTML ---
def extract_text_from_html(filepath):
"""Reads an HTML file, extracts plain text."""
try:
# Use 'utf-8' encoding as it's common for web pages
with open(filepath, 'r', encoding='utf-8') as f:
html_content = f.read()
# Parse HTML using BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
# Get text content, removing script and style tags
for script_or_style in soup(["script", "style"]):
script_or_style.extract() # Remove these elements
text = soup.get_text()
# Clean up whitespace: replace multiple spaces/newlines with single space
text = re.sub(r'\s+', ' ', text).strip()
return text
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return None
except Exception as e:
print(f"Error reading or parsing {filepath}: {e}")
return None
# --- Function to get words and fourgrams ---
def get_words_and_fourgrams(text):
"""Splits text into words, converts to lowercase, and generates fourgrams."""
if not text:
return []
# Split by non-word characters, convert to lowercase, filter out empty strings
words = [word for word in re.split(r'\W+', text.lower()) if word]
fourgrams = []
# Generate fourgrams (sequence of 4 words)
if len(words) >= 4:
for i in range(len(words) - 3):
fourgram_words = words[i:i+4]
fourgram_string = " ".join(fourgram_words)
fourgrams.append(fourgram_string)
return fourgrams
# --- Main Processing Logic ---
# Check if the source directory exists
if not os.path.isdir(source_directory):
print(f"Error: Directory not found at {source_directory}")
exit()
print(f"Starting processing of .htm files in {source_directory}...")
# Iterate through all files in the directory
for filename in os.listdir(source_directory):
# Check if the file ends with ".htm"
if filename.lower().endswith(".htm"):
filepath = os.path.join(source_directory, filename)
print(f"Processing file: {filepath}")
# Extract text
text_content = extract_text_from_html(filepath)
if text_content:
# Get fourgrams from the text
fourgrams_list = get_words_and_fourgrams(text_content)
# Update the global counter
all_fourgrams_counter.update(fourgrams_list)
print(f" Found {len(fourgrams_list)} fourgrams in {filename}. Total unique fourgrams counted so far: {len(all_fourgrams_counter)}")
else:
print(f" Skipping {filename} due to error or empty content.")
print("\nFinished processing files. Starting database operations...")
# --- Database Operations ---
conn = None # Initialize connection to None
try:
# Connect to the SQLite database (creates it if it doesn't exist)
print(f"Connecting to database: {database_path}")
conn = sqlite3.connect(database_path)
cursor = conn.cursor()
# Create the table if it doesn't exist
create_table_sql = f"""
CREATE TABLE IF NOT EXISTS {table_name} (
fourgram TEXT PRIMARY KEY,
count INTEGER
);
"""
cursor.execute(create_table_sql)
conn.commit()
print(f"Table '{table_name}' checked/created.")
# Filter fourgrams with count > min_count_threshold and prepare data for insertion
data_to_insert = []
for fourgram, count in all_fourgrams_counter.items():
if count > min_count_threshold: # Condition is "exceeds 5", so count >= 6
data_to_insert.append((fourgram, count))
# Insert or replace the fourgrams into the database
# Using INSERT OR REPLACE to handle cases where a fourgram might somehow appear twice
# in the list (though Counter prevents this), or if the script is run again later.
insert_sql = f"""
INSERT OR REPLACE INTO {table_name} (fourgram, count)
VALUES (?, ?);
"""
if data_to_insert:
print(f"Inserting {len(data_to_insert)} fourgrams with count exceeding {min_count_threshold}...")
cursor.executemany(insert_sql, data_to_insert)
conn.commit()
print("Database insertion complete.")
else:
print(f"No fourgrams found with count exceeding {min_count_threshold}.")
except sqlite3.Error as se:
print(f"Database error: {se}")
if conn:
conn.rollback() # Rollback any changes if an error occurred
except Exception as e:
print(f"An unexpected error occurred during database operations: {e}")
finally:
# Close the database connection
if conn:
conn.close()
print("Database connection closed.")
print("\nScript finished.")
Explanation:
Import Libraries:
os: To interact with the operating system (listing files, joining paths).
sqlite3: To work with SQLite databases.
BeautifulSoup from bs4: For parsing HTML content robustly. Install it if you don't have it (pip install beautifulsoup4).
Counter from collections: An efficient way to count hashable objects (our fourgram strings).
re: For regular expressions, used here to split text into words.
Configuration:
source_directory: Specifies the directory to scan. Using r"..." makes it a raw string, so backslashes are treated literally, which is good for Windows paths.
database_path: The name/path for the SQLite database file.
table_name: The name of the table within the database.
min_count_threshold: The minimum count a fourgram must exceed (> 5, so >= 6) to be stored.
all_fourgrams_counter: A Counter object initialized to store the counts of all unique fourgrams found across all processed files.
extract_text_from_html(filepath):
Takes a file path.
Opens the file, specifying encoding='utf-8' which is standard for web content. Includes error handling for FileNotFoundError and general exceptions during reading.
Uses BeautifulSoup to parse the HTML. html.parser is Python's built-in parser.
Removes <script> and <style> tags as their content is usually not part of the visible text flow.
Calls .get_text() to extract all the text content from the HTML structure.
Uses re.sub to replace sequences of whitespace characters (spaces, newlines, tabs) with a single space and then .strip() to remove leading/trailing whitespace.
Returns the cleaned plain text or None if an error occurred.
get_words_and_fourgrams(text):
Takes the plain text content.
Converts the text to lowercase ().
To run this script:
Save it as a Python file (e.g., fourgram_analyzer.py).
Make sure you have the beautifulsoup4 library installed (pip install beautifulsoup4).
Ensure the directory D:\Progr\Auto exists and contains .htm files.
Run the script from your terminal: python fourgram_analyzer.py.
A file named fourgrams.db will be created in the same directory where you run the script (or the specified database_path). You can then use an SQLite database viewer (like DB Browser for SQLite) to open fourgrams.db and view the fourgrams table.
Uses re.split(r'\W+', text.lower()) to split the text into words. \W+ matches one or more non-word characters. This handles punctuation and spaces as delimiters.
A list comprehension [word for word in ... if word] is used to filter out any empty strings that might result from the split (e.g., if the text starts/ends with punctuation or has multiple delimiters together).
It then iterates through the list of words, creating 4-word sequences (fourgrams) by taking slices words[i:i+4].
Each fourgram list is joined back into a single string using " ".join(...).
Returns a list of fourgram strings.
Main Processing Loop:
Checks if the source_directory exists.
Iterates through the entries in the directory using os.listdir().
Checks if the filename ends with .htm (case-insensitive check with .lower()).
Constructs the full filepath using os.path.join().
Calls extract_text_from_html to get the text content.
If text is successfully extracted, calls get_words_and_fourgrams to get the fourgrams.
Uses all_fourgrams_counter.update(fourgrams_list) to efficiently add the counts of the fourgrams found in the current file to the total counter.
Database Operations:
Uses a try...except...finally block to manage the database connection and handle potential errors.
sqlite3.connect(database_path): Establishes a connection. If fourgrams.db doesn't exist, it's created.
conn.cursor(): Creates a cursor object to execute SQL commands.
CREATE TABLE IF NOT EXISTS ...: Executes an SQL command to create the fourgrams table if it doesn't already exist.
fourgram TEXT PRIMARY KEY: Defines a column for the fourgram text, making it the primary key to ensure each fourgram is unique in the table.
count INTEGER: Defines a column for the count.
conn.commit(): Saves the table creation change.
It iterates through the all_fourgrams_counter.items().
if count > min_count_threshold:: Filters for fourgrams whose count is greater than 5.
data_to_insert.append((fourgram, count)): Creates a list of tuples (fourgram_string, count) ready for insertion.
INSERT OR REPLACE INTO ... VALUES (?, ?): The SQL command for inserting data. ? are placeholders for values. INSERT OR REPLACE will insert a new row if the fourgram doesn't exist or update the row if it does (this is slightly safer than just INSERT though Counter ensures uniqueness in the current run).
cursor.executemany(insert_sql, data_to_insert): This is the efficient way to insert multiple rows from a list of tuples.
conn.commit(): Saves the inserted data permanently to the database file.
Error handling for sqlite3.Error is included, with conn.rollback() to undo changes if an error occurs during database operations.
The finally block ensures conn.close() is called to release the database connection, whether successful or not.