# Simple Spellchecker

This utility provides a simple command-line spellchecker using the `pyspellchecker` library. It can identify misspelled words in a text string or file and suggest corrections.

**Modules Used:**
*   `pyspellchecker`: To check spelling and generate candidates.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.
*   `re`: To tokenize text (split into words).

## Installation

```bash
pip install pyspellchecker
```

## The Code

Save this as `spellcheck.py`.

```python
from spellchecker import SpellChecker
import argparse
import re
import os

def check_spelling(text, language='en'):
    try:
        spell = SpellChecker(language=language)
    except ValueError:
        print(f"Error: Language '{language}' not supported.")
        return
    
    # Find words using regex to avoid punctuation issues
    # This regex matches words with apostrophes (e.g., "don't")
    words = re.findall(r"[a-zA-Z']+", text)
    
    # Find those that may be misspelled
    misspelled = spell.unknown(words)
    
    if not misspelled:
        print("No misspelled words found!")
        return

    print(f"Found {len(misspelled)} potential misspellings:\n")
    print(f"{'Word':<20} {'Suggestion':<20}")
    print("-" * 40)

    for word in misspelled:
        # Get the one `most likely` answer
        correction = spell.correction(word)
        
        # Handle case where correction might be None
        if correction is None:
            correction = "(No suggestion)"
            
        print(f"{word:<20} {correction:<20}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple Spellchecker")
    parser.add_argument("input", help="Text to check OR path to a text file")
    parser.add_argument("-l", "--lang", default="en", help="Language code (default: en)")
    
    args = parser.parse_args()
    
    # Check if input is a file path
    text_data = args.input
    if os.path.isfile(args.input):
        try:
            with open(args.input, 'r', encoding='utf-8') as f:
                text_data = f.read()
            print(f"Checking file: {args.input}...")
        except Exception as e:
            print(f"Error reading file: {e}")
            exit(1)

    check_spelling(text_data, args.lang)
```

## Usage

```bash
# Check a sentence
python spellcheck.py "This is a sentance with some erors."

# Check a file
python spellcheck.py document.txt
```

[[programming/python/python]]