Snehal Ingle
Snehal Ingle

Reputation: 31

Create a meaningful sentence containing specific word in python

I'm working on a project, where I have a word (Ex. apotheosis) Although I have the meaning for the word, I also want to display a sentence which uses the specific word in it (Ex. I think that he is enjoying his apotheosis).

Is there a python library to achieve this?

Upvotes: 2

Views: 141

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22370

You could try scrape https://www.wordreference.com/definition/apotheosis:

import requests
from bs4 import BeautifulSoup
from requests.exceptions import HTTPError


BASE_WORDREFERENCE_URL = 'https://www.wordreference.com/definition/'
EXAMPLE_USAGE_CLASS = 'rh_ex'


def get_example_usages(word: str) -> list[str]:
    url = f'{BASE_WORDREFERENCE_URL}{word}'
    try:
        page = requests.get(url)
        page.raise_for_status()
    except HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')
    except Exception as err:
        print(f'Other error occurred: {err}')
    else:
        soup = BeautifulSoup(page.content, 'html.parser')
        example_usages = soup.find_all('span', class_=EXAMPLE_USAGE_CLASS)
        if not example_usages:
            raise ValueError(f'No example usages found for {word}')
        return [e.text for e in example_usages]


def main() -> None:
    word = input('Enter a word to lookup example usages: ')
    print(get_example_usages(word))


if __name__ == '__main__':
    main()

Example Usage:

Enter a word to lookup example usages: apotheosis
['This poem is the apotheosis of lyric expression.']

Upvotes: 1

Snehal Ingle
Snehal Ingle

Reputation: 31

Actually, after searching on google, I found this service (for example, sentences, related words, and many more)

http://developer.wordnik.com/docs#

Upvotes: 1

Related Questions