import os
import re
import sqlite3
from collections import Counter
def extract_bigrams(text):
"""
Extracts bigrams from a given text.
Args:
text: The input text string.
Returns:
A list of bigrams.
"""
# Remove HTML tags and punctuation, convert to lowercase
text = re.sub('<[^<]+?>', '', text) # Remove HTML tags
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
text = text.lower()
words = text.split()
bigrams = list(zip(words, words[1:]))
return bigrams
def process_htm_files(directory, db_path):
"""
Reads all .htm files in a directory, extracts bigrams, and writes
unique bigrams with counts > 10 to an SQLite database.
Args:
directory: The directory containing the .htm files.
db_path: The path to the SQLite database file.
"""
all_bigrams = []
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 f:
text = f.read()
bigrams = extract_bigrams(text)
all_bigrams.extend(bigrams)
except Exception as e:
print(f"Error reading or processing file {filename}: {e}")
# Count bigram occurrences
bigram_counts = Counter(all_bigrams)
# Connect to the SQLite database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create the table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS bigrams (
bigram TEXT PRIMARY KEY,
count INTEGER
)
''')
# Insert or update bigrams with counts > 10
for bigram, count in bigram_counts.items():
if count > 10:
bigram_str = " ".join(bigram) # Convert tuple to string for storage
try:
cursor.execute("INSERT OR REPLACE INTO bigrams (bigram, count) VALUES (?, ?)", (bigram_str, count))
except Exception as e:
print(f"Error inserting/updating bigram {bigram_str}: {e}")
# Commit the changes and close the connection
conn.commit()
conn.close()
if __name__ == "__main__":
directory_path = r"D:\Progr\Auto" # Replace with your directory path
database_path = "bigrams.db"
process_htm_files(directory_path, database_path)
print("Bigram extraction and database update complete.")
Key improvements and explanations:
- Error Handling: Includes
try...except blocks to handle potential errors when reading files (e.g., file not found, permission issues, encoding errors) and when inserting/updating the database. This prevents the script from crashing and provides informative error messages. The encoding='utf-8' is crucial for handling a wider range of characters in HTML files.
- HTML Tag Removal: Uses
re.sub('<[^<]+?>', '', text) to reliably remove HTML tags. This is important because HTML tags would otherwise be included in the bigrams, which is not what you want.
- Punctuation Removal: Removes punctuation using
re.sub(r'[^\w\s]', '', text). This cleans the text for more accurate bigram extraction.
- Case Insensitivity: Converts the text to lowercase using
text.lower() to ensure that "The" and "the" are treated as the same bigram.
- Bigram Extraction: The
extract_bigrams function now correctly extracts bigrams using zip.
- Database Interaction:
CREATE TABLE IF NOT EXISTS: Creates the bigrams table only if it doesn't already exist, preventing errors on subsequent runs.
INSERT OR REPLACE: Uses INSERT OR REPLACE to either insert a new bigram or update the count if the bigram already exists in the database. This is much more efficient than checking for existence first.
- String Conversion: Converts the bigram tuple to a string using
" ".join(bigram) before storing it in the database. SQLite doesn't directly support tuple primary keys.
- Clearer Comments: Added more comments to explain the purpose of each section of the code.
if __name__ == "__main__": block: This ensures that the process_htm_files function is only called when the script is run directly (not when it's imported as a module).
Counter for Efficient Counting: Uses collections.Counter to efficiently count the occurrences of each bigram.
- Encoding: Specifies
encoding='utf-8' when opening files to handle a wider range of characters.
- Path Handling: Uses
os.path.join to create file paths, which is more portable and reliable than string concatenation.
- Informative Output: Prints a message when the process is complete.
How to run the script:
- Install
sqlite3: Python usually comes with sqlite3 pre-installed. If not, you might need to install it using your system's package manager (e.g., apt-get install sqlite3 on Debian/Ubuntu).
- Save the script: Save the code as a
.py file (e.g., bigram_extractor.py).
- Modify the paths: Change
directory_path to the actual path of your "Auto" directory and database_path if you want to save the database in a different location.
- Run the script: Open a terminal or command prompt, navigate to the directory where you saved the script, and run it using
python bigram_extractor.py.
This revised script is much more robust, efficient, and easier to understand. It addresses the potential issues in the previous versions and provides better error handling. Remember to replace the placeholder directory path with your actual path.