If you need to get dictionary definitions of words in Python, there are several packages available that make this task easy. These packages allow you to look up meanings, synonyms, antonyms, and even translations of words programmatically.
PyDictionary
PyDictionary is one of the most popular Python modules for getting word definitions.
Installation
bash
pip install PyDictionary
Basic Usage
python
from PyDictionary import PyDictionary
# Create a dictionary instance
dictionary = PyDictionary()
# Get meaning of a word
word_meaning = dictionary.meaning("indentation")
print(word_meaning)
This will return a dictionary with word types as keys and definitions as values[5][11]:
python
{
'Noun': [
'a concave cut into a surface or edge (as in a coastline',
'the formation of small pits in a surface as a consequence of corrosion',
'the space left between the margin and the start of an indented line',
'the act of cutting into an edge with toothlike notches or angular incisions'
]
}
Getting Synonyms and Antonyms
python
# Get synonyms
synonyms = dictionary.synonym("life")
print(synonyms)
# Get antonyms
antonyms = dictionary.antonym("life")
print(antonyms)
Translations
python
# Translate a word to Spanish
translation = dictionary.translate("range", 'es')
print(translation)
Working with Multiple Words
You can also initialize PyDictionary with multiple words[5][11]:
python
dictionary = PyDictionary("hotel", "ambush", "nonchalant", "perceptive")
print(dictionary.printMeanings()) # Print meanings of all words
print(dictionary.getMeanings()) # Return meanings as dictionaries
print(dictionary.getSynonyms()) # Get synonyms
print(dictionary.translateTo("hi")) # Translate all words to Hindi
Getting a Single Meaning
If you want just one meaning instead of all definitions[13]:
python
word_definitions = dictionary.meaning('book')
# Get the first noun definition if available
first_noun_definition = word_definitions.get('Noun', ['No definition found'])
print(first_noun_definition)
PyMultiDictionary
PyMultiDictionary supports word definitions in 20 different languages, making it more versatile for multilingual applications.
from PyMultiDictionary import MultiDictionary, DICT_MW
# Create a dictionary instance
dictionary = MultiDictionary()
# Get meaning of an English word
meaning = dictionary.meaning('en', 'good')
print(meaning)
# Using alternative dictionary source (Merriam-Webster)
mw_meaning = dictionary.meaning('en', 'good', dictionary=DICT_MW)
print(mw_meaning)
# Get synonyms in Spanish
synonyms = dictionary.synonym('es', 'Bueno')
print(synonyms)
# Get translations
translations = dictionary.translate('en', 'Range')
print(translations)
# Translate to a specific language (Russian)
russian_translation = dictionary.translate('en', 'Range', to='ru')
print(russian_translation)
PyMultiDictionary returns meanings in a tuple format containing word type, meaning, and Wikipedia information[10].
Using Dictionary APIs
Another approach is to use web APIs to fetch dictionary definitions:
python
import requests
def get_word_definition(word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 200:
data = response.json()
return data['meanings']['definitions']['definition']
else:
return "Definition not found"
# Example usage
definition = get_word_definition("python")
print(definition)
Text-to-Speech Dictionary Application
You can combine dictionary lookups with text-to-speech for a more interactive experience[14][15]:
python
import pyttsx3
from PyDictionary import PyDictionary
def get_word_definition(word):
dictionary = PyDictionary()
definition = dictionary.meaning(word)
if definition:
return definition.get('Noun', ['No definition found'])
else:
return 'No definition found'
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def main():
prompt_text = "Which word do you want to find the meaning of? Please write the word and I will wait."
text_to_speech(prompt_text)
print(prompt_text)
word = input("Word: ").strip()
if word:
definition = get_word_definition(word)
print(f"Definition: {definition}")
text_to_speech(definition)
else:
print("No word provided.")
if __name__ == "__main__":
main()
Other Dictionary Packages
AyDictionary
bash
pip install AyDictionary googletrans==4.0.0-rc1
python
from AyDictionary import AyDictionary
dictionary = AyDictionary()
meaning = dictionary.meaning("python")
print(f"Meaning of 'python': {meaning}")
Using Python's Built-in Dictionary Type
Note that while not for word definitions, Python's built-in dictionary data type can be used to create your own dictionary of words and definitions:
python
my_dictionary = {
"python": "A high-level programming language",
"dictionary": "A collection of key-value pairs",
"API": "Application Programming Interface"
}
# Get definition
print(my_dictionary.get("python", "Word not found"))
Handling Edge Cases
When working with dictionary APIs, it's important to handle cases where words aren't found:
python
from PyDictionary import PyDictionary
dictionary = PyDictionary()
def safe_get_meaning(word):
try:
meaning = dictionary.meaning(word)
if meaning:
return meaning
else:
return f"No meaning found for '{word}'"
except Exception as e:
return f"Error looking up '{word}': {str(e)}"
# Test with valid and invalid words
print(safe_get_meaning("python"))
print(safe_get_meaning("xyzabc123")) # Likely not a real word
Each of these packages has different strengths - PyDictionary is simple and easy to use, PyMultiDictionary offers multi-language support, and using APIs gives you more control but requires internet connectivity. Choose the one that best fits your specific requirements.