python Copy code
import os
import re
import sqlite3
from bs4 import BeautifulSoup
def extract_sentences_from_htm(file_path):
"""Extract sentences from an HTM file."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Parse HTML content
soup = BeautifulSoup(content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get text and split into sentences
text = soup.get_text()
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s', text)
# Clean sentences
cleaned_sentences = []
for sentence in sentences:
sentence = sentence.strip()
if sentence: # Skip empty sentences
cleaned_sentences.append(sentence)
return cleaned_sentences
def process_directory(directory_path):
"""Process all HTM files in a directory and return sentence counts."""
sentence_counts = {}
for filename in os.listdir(directory_path):
if filename.lower().endswith('.htm'):
file_path = os.path.join(directory_path, filename)
try:
sentences = extract_sentences_from_htm(file_path)
for sentence in sentences:
sentence_counts[sentence] = sentence_counts.get(sentence, 0) + 1
except Exception as e:
print(f"Error processing {filename}: {e}")
return sentence_counts
def store_in_database(sentence_counts, db_path):
"""Store sentence counts in SQLite database."""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS clauses (
clause TEXT PRIMARY KEY,
count INTEGER
)
''')
# Insert or update sentences
for sentence, count in sentence_counts.items():
cursor.execute('''
INSERT OR REPLACE INTO clauses (clause, count)
VALUES (?, COALESCE((SELECT count FROM clauses WHERE clause = ?), 0) + ?)
''', (sentence, sentence, count))
conn.commit()
conn.close()
def main():
directory_path = r"D:\Progr\Auto"
db_path = "clauses.db"
if not os.path.exists(directory_path):
print(f"Directory not found: {directory_path}")
return
print("Processing HTM files...")
sentence_counts = process_directory(directory_path)
print("Storing in database...")
store_in_database(sentence_counts, db_path)
print(f"Done! Processed {len(sentence_counts)} unique sentences.")
if __name__ == "__main__":
main()
To run this script, you'll need to install the following packages if you haven't already: