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