Created
June 6, 2017 04:02
-
-
Save mathandy/d226b54224c73e52e86577cb96666139 to your computer and use it in GitHub Desktop.
Scrape the definition of a word (or phrase) from dictionary.com using Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Scrape the definition of a word (or phrase) from dictionary.com | |
Usage: | |
====== | |
python define.py onomatopoeia | |
Warning: | |
======== | |
Sometimes (at least with phrases) you'll be unexpectedly redirected | |
to the definition of another only loosely related word, | |
e.g. try defining "over the hill".""" | |
from __future__ import print_function | |
try: input = raw_input | |
except: pass | |
import re | |
from urllib2 import urlopen | |
def define(word): | |
"""Scrape the definition of a word from dictionary.com""" | |
word = word.replace(' ', '--') | |
try: | |
html = urlopen("http://dictionary.reference.com/browse/" + word).read() | |
except: | |
print('\nEither this code is out-of-date or dictionary.com ' | |
'does not know what "%s" means.\n' % word) | |
return | |
items=re.findall('<div class="def-content">\s.*?</div>', html, re.S) | |
defs = [re.sub('<.*?>','', x).strip() for x in items] | |
for i, d in enumerate(defs): | |
print('\n', '%s'%(i+1), d) | |
if __name__ == '__main__': | |
import sys | |
if len(sys.argv) > 1: | |
define('--'.join(sys.argv[1:])) | |
else: | |
define(input("Enter the word you'd like to define: ")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment