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.
To solve this problem, we need to extract trigrams from all .htm files in a specified directory, count their occurrences across these files, and store the unique trigrams with counts greater than 5 into an SQLite database. Here's the step-by-step solution:
Approach
Directory Traversal: Identify all .htm files in the target directory.
Text Processing: For each file, read its content, convert it to lowercase, and split into words.
Trigram Extraction: Generate trigrams by grouping three consecutive words from the word list.
Counting Trigram Frequencies: Use a dictionary to count occurrences of each trigram across all files.
Database Operations: Create an SQLite database with a table to store trigrams and their counts. Insert trigrams with counts exceeding 5.
Solution Code
python
import os
import sqlite3
import re
def extract_trigrams(text):
words = re.findall(r'\b\w+\b', text.lower())
return [' '.join(words[i:i+3]) for i in range(len(words) - 2)]
def main():
directory = r"D:\Progr\Auto"
trigram_counts = {}
for filename in os.listdir(directory):
if filename.endswith(".htm"):
filepath = os.path.join(directory, filename)
try:
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
trigrams = extract_trigrams(content)
for trigram in trigrams:
trigram_counts[trigram] = trigram_counts.get(trigram, 0) + 1
except Exception as e:
print(f"Error processing {filename}: {e}")
filtered_trigrams = {t: c for t, c in trigram_counts.items() if c > 5}
db_path = "trigrams.db"
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("CREATE TABLE trigrams (trigram TEXT PRIMARY KEY, count INTEGER)")
for trigram, count in filtered_trigrams.items():
cursor.execute("INSERT INTO trigrams (trigram, count) VALUES (?, ?)", (trigram, count))
conn.commit()
print(f"Inserted {len(filtered_trigrams)} trigrams into database.")
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
if __name__ == "__main__":
main()
Explanation
extract_trigrams Function:
Processes input text by converting to lowercase and extracting words using a regular expression.
Generates trigrams by combining each set of three consecutive words.
Main Function:
File Processing: Iterates over all .htm files in the specified directory. Each file's content is read and split into trigrams.
Counting Trigram Frequencies: Uses a dictionary to accumulate counts of each trigram encountered.
Filtering: Retains only trigrams with counts greater than 5.
Database Handling:
Creates a new SQLite database trigrams.db.
Defines a table trigrams with columns trigram (text) and count (integer).
Inserts filtered trigrams into the table and commits the changes.
Error Handling:
Skips files that cause read errors and logs the issue.
Catches and reports database-related errors during table creation or data insertion.
This approach efficiently processes HTML files, extracts meaningful trigrams, and stores them in a structured database while ensuring robustness through error handling.