symspellpy Documentation

repository·master·Indexed 21 days ago

https://github.com/mammothb/symspellpy

A high-performance Python port of the SymSpell algorithm (v6.7.2) designed for fast and memory-efficient spelling correction and edit distance calculations. It provides tools for single-word and compound lookups, frequency and bigram dictionary loading, and supports multiple edit distance algorithms including Levenshtein and Damerau-Osa. Users can also implement custom distance comparers by subclassing AbstractDistanceComparer.

Tokens
14K
Snippets
45
Records
58
Agent score
74%

What's inside symspellpy

  1. Overview of symspellpy

    master
    symspellpy is a Python port of SymSpell v6.7.2. It implements the Symmetric Delete spelling correction algorithm, which is designed for high speed and low memory consumption. The port aims to replicate the code structure of the original SymSpell project and includes unit tests from the original project to ensure accuracy.
  2. Use external dictionary files

    master

    If you prefer not to use the files shipped with the package, you can download the dictionary files directly from the GitHub repository and include them in your own project directory.

    Example project layout:

    project_dir
    +-frequency_bigramdictionary_en_243_342.txt
    +-frequency_dictionary_en_82_765.txt
    \-project.py
    curl -LJO https://raw.githubusercontent.com/mammothb/symspellpy/master/symspellpy/frequency_dictionary_en_82_765.txt
    curl -LJO https://raw.githubusercontent.com/mammothb/symspellpy/master/symspellpy/frequency_bigramdictionary_en_243_342.txt
  3. Access shipped dictionary data

    master

    The dictionary files included with the symspellpy package can be accessed programmatically using importlib.resources. This is the recommended way to locate the frequency and bigram dictionaries shipped with the library.

    import importlib.resources
    
    dictionary_path = importlib.resources.files("symspellpy") / "frequency_dictionary_en_82_765.txt"
    bigram_path = importlib.resources.files("symspellpy") / "frequency_bigramdictionary_en_243_342.txt"
  4. Implement a custom distance comparer

    master

    To use a custom algorithm for calculating string distances in symspellpy, you must create a class that inherits from AbstractDistanceComparer and implements the distance(self, string_1, string_2, max_distance) method.

    Once implemented, you pass this comparer to the Editdistance class using the DistanceAlgorithm.USER_PROVIDED flag. Finally, initialize SymSpell with this custom Editdistance instance as the distance_comparer argument.

    import importlib.resources
    from symspellpy import SymSpell
    from symspellpy.abstract_distance_comparer import AbstractDistanceComparer
    from symspellpy.editdistance import DistanceAlgorithm, Editdistance
    
    class CustomComparer(AbstractDistanceComparer):
        def distance(self, string_1, string_2, max_distance):
            # Implement your custom logic here
            # Example: return distance if within max_distance, else -1
            distance = ... 
            return -1 if distance > max_distance else distance
    
    # 1. Wrap the custom comparer in Editdistance with USER_PROVIDED algorithm
    custom_comparer = Editdistance(DistanceAlgorithm.USER_PROVIDED, CustomComparer())
    
    # 2. Inject the custom comparer into SymSpell
    sym_spell = SymSpell(distance_comparer=custom_comparer)
  5. Install symspellpy via pip

    master

    You can install the official release of symspellpy and its dependencies using pip. The package is available as wheel packages for macOS, Windows, and Linux distributions.

    Note: While available for macOS, symspellpy has only been explicitly tested on Windows and Linux systems.

    python -m pip install -U symspellpy
  6. Implement a custom distance algorithm

    master

    If you need a specific distance metric not provided by the library, you can implement your own by subclassing AbstractDistanceComparer and implementing the distance(string_1, string_2, max_distance) method. Then, use DistanceAlgorithm.USER_PROVIDED to inject it into EditDistance.

    Note: If you pass a comparer to EditDistance but do not set the algorithm to USER_PROVIDED, a warning will be issued and your comparer will be ignored in favor of the built-in algorithm.

    from symspellpy.editdistance import EditDistance, DistanceAlgorithm
    from symspellpy.abstract_distance_comparer import AbstractDistanceComparer
    
    class MyCustomComparer(AbstractDistanceComparer):
        def distance(self, string_1: str, string_2: str, max_distance: int) -> int:
            # Your custom logic here
            return 0
    
    custom_comparer = MyCustomComparer()
    edist = EditDistance(DistanceAlgorithm.USER_PROVIDED, comparer=custom_comparer)
    print(edist.compare("a", "b", 1))
  7. Install editdistpy for fast distance algorithms

    master

    The LEVENSHTEIN_FAST and DAMERAU_OSA_FAST algorithms are wrappers around the editdistpy library. If you attempt to use them without this dependency, an ImportError will be raised.

    To install the necessary dependency, use:

    pip install symspellpy[editdistpy]
    pip install symspellpy[editdistpy]
  8. Return original word if no correction is found

    master

    By default, lookup returns an empty list if no correction is found within the specified edit distance. To ensure the original word is returned as a suggestion even when no correction is found, set include_unknown=True in the lookup method.

    import importlib.resources
    from symspellpy import SymSpell, Verbosity
    
    sym_spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7)
    dictionary_path = importlib.resources("symspellpy") / "frequency_dictionary_en_82_765.txt"
    sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
    
    input_term = "apastraphee"  # misspelling of "apostrophe"
    suggestions = sym_spell.lookup(
        input_term, Verbosity.CLOSEST, max_edit_distance=2, include_unknown=True
    )
    for suggestion in suggestions:
        print(suggestion)
  9. Perform word segmentation with SymSpell

    master

    You can use the word_segmentation method to split a continuous string of characters (a sentence without spaces) into individual words.

    To ensure the segmentation process only splits words and does not attempt to correct spelling, initialize SymSpell with max_dictionary_edit_distance=0.

    When loading a dictionary via load_dictionary, you must specify the term_index (the column containing the word) and the count_index (the column containing the term frequency).

    import importlib.resources
    from symspellpy.symspellpy import SymSpell
    
    # Initialize with max_dictionary_edit_distance=0 to avoid spelling correction
    sym_spell = SymSpell(max_dictionary_edit_distance=0, prefix_length=7)
    
    # Load the dictionary
    dictionary_path = importlib.resources("symspellpy") / "frequency_dictionary_en_82_765.txt"
    sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
    
    # Segment a string without spaces
    input_term = "thequickbrownfoxjumpsoverthelazydog"
    result = sym_spell.word_segmentation(input_term)
    
    # result contains corrected_string, distance_sum, and log_prob_sum
    print(f"{result.corrected_string}, {result.distance_sum}, {result.log_prob_sum}")
  10. Avoid correcting phrases matching regex using ignore_token

    master

    You can prevent SymSpell from attempting to correct specific types of tokens (like alphanumeric strings) by providing a regular expression to the ignore_token parameter in the lookup method. If a token matches the regex, it will be returned as-is without correction attempts.

    import importlib.resources
    from symspellpy import SymSpell, Verbosity
    
    sym_spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7)
    dictionary_path = importlib.resources("symspellpy") / "frequency_dictionary_en_82_765.txt"
    sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
    
    input_term = "members1"
    suggestions = sym_spell.lookup(
        input_term, Verbosity.CLOSEST, max_edit_distance=2, ignore_token=r"\w+\d"
    )
    for suggestion in suggestions:
        print(suggestion)