Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Dictionary/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Dictionary

## How to use

Run the program with the command:

```python dictionary.py
```

Enter the word you want to look up when prompted. The program will return the definition of the word if it exists in the dictionary.

## Quirks

- Certain word definitions may contain multiple meanings, and the program will return only the first definition, but **only** in certain cases. In other cases, it may return all definitions. This inconsistency is due to the way the dictionary data is structured and how the program processes it.
45 changes: 45 additions & 0 deletions Dictionary/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""This program fetches the definition of a word from the Dictionary API
and displays it to the user.
The user is prompted to enter a word, and the program makes a GET request to the API
to retrieve the definition.
The program then extracts and displays the word,
its phonetics, and the number of meanings it has."""
# many line breaks here because the default line length is
# 100 characters but the docstring is longer than that lol
import requests

URL = "https://api.dictionaryapi.dev/api/v2/entries/en/"

def get_definition(word):
"""Fetches the definition of a word from the Dictionary API and displays it to the user."""
response = requests.get(f"{URL}{word}", timeout=10)
if response.status_code == 200:
data = response.json()
# print(data)
word1 = data[0]['word']
phonetics = data[0]['phonetics'][1]['text']
number_of_meanings = len(data[0]['meanings'])
print(f"Word: {word1}")
print(f"Phonetics: {phonetics}")
print(f"Number of meanings: {number_of_meanings}")
for i in range(0, number_of_meanings):
try:
meaning = data[0]['meanings'][i]
definition = meaning['definitions'][i]
antonyms = definition.get('antonyms') or 'No antonyms'
print(
f"Meaning {i}: {meaning.get('partOfSpeech','')} "
f"Definition {i}: {definition.get('definition','')} "
f"Antonyms: {antonyms}"
)
# for definition in meaning['definitions']:
# print(f"Definition: {definition['definition']}")
except IndexError:
continue

def main():
"""Main function to run the program."""
word = input("Enter a word to get its definition: ")
get_definition(word)

main()
Loading