Write the script in Python that reads all the files "htm" in the directory "D:\Progr\Auto", extracts the sentences from them and writes the unique sentences and their count to the respective cells "clause" and "count" of the table "clauses" in the SQLite database "clauses.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.
Here's a Python script that accomplishes your requirements:
python
import os
import sqlite3
import re
from bs4 import BeautifulSoup
from collections import Counter
def create_database():
"""Create SQLite database and table if they don't exist"""
conn = sqlite3.connect('clauses.db')
cursor = conn.cursor()
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS clauses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
clause TEXT UNIQUE,
count INTEGER
)
''')
conn.commit()
return conn, cursor
def extract_sentences(html_content):
"""Extract sentences from HTML content"""
# Parse HTML
soup = BeautifulSoup(html_content, 'html.parser')
# Get text content
text = soup.get_text()
# Split into sentences
# This regex looks for sentence endings (.!?) followed by whitespace or end of string
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
# Clean sentences and filter out empty ones
cleaned_sentences = []
for sentence in sentences:
sentence = sentence.strip()
if sentence and len(sentence) > 5: # Filter out very short sentences
cleaned_sentences.append(sentence)
return cleaned_sentences
def process_files(directory):
"""Process all HTM files in the directory"""
# Create database connection
conn, cursor = create_database()
# Dictionary to store sentence counts
sentence_counts = Counter()
try:
# Process each HTM file in the directory
for filename in os.listdir(directory):
if filename.lower().endswith('.htm') or filename.lower().endswith('.html'):
file_path = os.path.join(directory, filename)
print(f"Processing {filename}...")
try:
# Read file content
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Extract sentences
sentences = extract_sentences(content)
# Update sentence counts
sentence_counts.update(sentences)
except Exception as e:
print(f"Error processing {filename}: {str(e)}")
# Insert or update sentences in database
for sentence, count in sentence_counts.items():
try:
# Try to insert new record
cursor.execute('''
INSERT INTO clauses (clause, count)
VALUES (?, ?)
ON CONFLICT(clause) DO UPDATE SET count = count + ?
''', (sentence, count, count))
except sqlite3.Error as e:
print(f"Error inserting sentence: {str(e)}")
# Commit changes
conn.commit()
print(f"Processed {len(sentence_counts)} unique sentences")
finally:
# Close database connection
conn.close()
def main():
directory = r"D:\Progr\Auto"
# Verify directory exists
if not os.path.exists(directory):
print(f"Directory {directory} does not exist")
return
process_files(directory)
print("Processing complete!")
if __name__ == "__main__":
main()
This script does the following:
Required libraries:
os for file operations
sqlite3 for database operations
re for regular expressions
BeautifulSoup for HTML parsing
Counter from collections for counting sentences
Functions:
create_database(): Creates the SQLite database and table if they don't exist
extract_sentences(): Extracts and cleans sentences from HTML content
process_files(): Processes all HTM files and updates the database
main(): Main execution function
Features:
Processes both .htm and .html files (case-insensitive)
Creates a SQLite database named "clauses.db"
Creates a table named "clauses" with columns: id, clause, and count
Extracts sentences using HTML parsing and regular expressions
Counts unique sentences across all files
Handles errors gracefully
Uses UPSERT (INSERT or UPDATE) to handle existing sentences
Filters out very short sentences (less than 5 characters)
Ensure you have write permissions in the directory where the script runs (for the database)
Have the correct path to your HTM files
The script will:
Create a database file named "clauses.db" in the same directory as the script
Process all HTM/HTML files in the specified directory
Store unique sentences and their counts in the database
Print progress information
To run the script, save it and execute it with Python. The script will create the database and populate it with the sentences found in your HTM files.
Note: You might need to adjust the sentence extraction logic (extract_sentences function) depending on your specific needs, as sentence boundary detection can be complex depending on your content.