Get similar words suggestion using Enchant in Python
In this tutorial, we will learn how to get similar words suggestion in Python using Enchant.
In Python, Enchant suggests words that have nearly similar spelling as of the given word. This module consists of dictionaries of many languages. For suggestions of similar words, it uses suggest() method that searches similar words among all the words available in a particular dictionary.
For example:
For the word: speed suggested words are: ['speed', 'sped', 'seed', 'peed', 'speeds', 'spreed', 'speedy', 'spewed', 'spied', 'spend', 'steed', 'spued', 's peed'] For the word: mango suggested words are: ['mange', 'manga', 'tango', 'mongo', 'mangy', 'fango', 'man go', 'man-go', 'mango']
Install enchant module:
‘pip’ command installs all the packages and additional dependencies needed.
To install enchant module in the system, run the given command on the command prompt:
!pip install pyenchant
Similar word suggestions in Python
Example1: Get the list of suggested words similar to the given word.
#import enchant module import enchant # dictionary is set to 'en_US' dict = enchant.Dict('en_US') # suggest() method give the similar words print(dict.suggest('color')) # dictionary is set to 'en_AU' dict = enchant .Dict('en_AU') # suggest() method gives the similar words print(dict.suggest('color'))
Output: ['color', 'colors', 'colon', 'dolor', 'col or', 'col-or'] ['colour', 'colon', 'col or', 'col-or', 'Colo']
Here, when the dictionary sets to ‘en_US’ using enchant.Dict() method, it returns the list of suggested words present in the ‘en_US’ dictionary similar to the word ‘color’. Similarly, when the dictionary is set to ‘en_AU’, it gives a list of the similar word present in ‘en_AU’ dictionary. The list of suggested words returned both the time are different. This shows that all the dictionaries of different languages have different sets of words available.
Example2: Get the list of suggested words similar to the word entered by the user.
#import enchant module import enchant def suggested_word(word): #dictionary is set to 'en_US' dict = enchant.Dict('en_US') # check the spelling of the given word if dict.check(word) == True: print('Correctly spelled') else: print('misspelled') # return list of suggested words return (dict.suggest(word)) w = input('Please enter the desired word:\n') print(suggested_word(w))
Output:
Please enter the desired word:
Input:
cartoon
Output:
Correctly spelled ['cartoon', 'carton', 'cartoons', 'cartoony', 'cardoon']
Also read: Create a spelling checker using Enchant in Python
Leave a Reply