symspellpy Documentation
repository·master·Indexed 21 days ago
https://github.com/mammothb/symspellpyA 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.
What's inside symspellpy
- 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.
Use external dictionary files
masterIf 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.pycurl -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.txtInstall symspellpy
masterTo installsymspellpy, refer to the official installation documentation or theINSTALL.rstfile in the repository. For the most up-to-date instructions, visit the install documentation.Access shipped dictionary data
masterThe dictionary files included with the
symspellpypackage can be accessed programmatically usingimportlib.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"Implement a custom distance comparer
masterTo use a custom algorithm for calculating string distances in
symspellpy, you must create a class that inherits fromAbstractDistanceComparerand implements thedistance(self, string_1, string_2, max_distance)method.Once implemented, you pass this comparer to the
Editdistanceclass using theDistanceAlgorithm.USER_PROVIDEDflag. Finally, initializeSymSpellwith this customEditdistanceinstance as thedistance_comparerargument.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)Get started with symspellpy usage examples
masterFor practical implementations and sample usage patterns, consult the official examples documentation.Install symspellpy via pip
masterYou can install the official release of
symspellpyand its dependencies usingpip. The package is available as wheel packages for macOS, Windows, and Linux distributions.Note: While available for macOS,
symspellpyhas only been explicitly tested on Windows and Linux systems.python -m pip install -U symspellpyImplement a custom distance algorithm
masterIf you need a specific distance metric not provided by the library, you can implement your own by subclassing
AbstractDistanceComparerand implementing thedistance(string_1, string_2, max_distance)method. Then, useDistanceAlgorithm.USER_PROVIDEDto inject it intoEditDistance.Note: If you pass a
comparertoEditDistancebut do not set the algorithm toUSER_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))Install editdistpy for fast distance algorithms
masterThe
LEVENSHTEIN_FASTandDAMERAU_OSA_FASTalgorithms are wrappers around theeditdistpylibrary. If you attempt to use them without this dependency, anImportErrorwill be raised.To install the necessary dependency, use:
pip install symspellpy[editdistpy]pip install symspellpy[editdistpy]Return original word if no correction is found
masterBy default,
lookupreturns 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, setinclude_unknown=Truein thelookupmethod.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)Perform word segmentation with SymSpell
masterYou can use the
word_segmentationmethod 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
SymSpellwithmax_dictionary_edit_distance=0.When loading a dictionary via
load_dictionary, you must specify theterm_index(the column containing the word) and thecount_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}")Avoid correcting phrases matching regex using ignore_token
masterYou can prevent
SymSpellfrom attempting to correct specific types of tokens (like alphanumeric strings) by providing a regular expression to theignore_tokenparameter in thelookupmethod. 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)