faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 12 people (58%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Dictionary lookup over the web

Jul 5th, 2000 10:01
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 191, Keith Dart


"""
Packages: networking.internet.cgi
"""
#!/usr/bin/python
"""
A relatively simple script that makes use of a dictionary.com CGI script
to build a command-line tool that returns the definition of a given word.
This uses the Python HTML parser modules. Python is just so cool. ;-)
"""
import sys, string, re
import urllib, httplib
from formatter import AbstractFormatter, DumbWriter
from htmllib import HTMLParser
if len(sys.argv) < 2:
	print "Usage: %s <word>" % (sys.argv[0])
	print "Where: <word> is the dictionary word you want to look up the"
	print "       definition of."
	print "The word is fetched from the dictionary.com web site."
	sys.exit(1)
BaseURL = "http://www.dictionary.com/cgi-bin/dict.pl?term="
try:
	ef = urllib.urlopen(BaseURL + urllib.quote_plus(string.strip(sys.argv[1])))
except:
	print "Cannot open URL."
	sys.exit(1)
entry = ef.readlines()
ef.close()
# The CGI output marks the beginning and end of each definition with these
# markers.  Take advantage of it to remove advertisements and junk. 8-)
re_start = re.compile(r'resultItemStart')
re_end = re.compile(r'resultItemEnd')
parsehtml = HTMLParser(AbstractFormatter(DumbWriter()))
printflag = 0
for line in entry:
	if re_start.search(line) != None:
		printflag = 1
	if re_end.search(line) != None:
		printflag = 0
		parsehtml.feed('<br><hr>')
	if printflag:
		parsehtml.feed(line)
# vim:ts=4:sw=4