Skip to content

Instantly share code, notes, and snippets.

@chromakode
Created January 16, 2009 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chromakode/47789 to your computer and use it in GitHub Desktop.
Save chromakode/47789 to your computer and use it in GitHub Desktop.
There's a running complaint in #reddittrivia that people are using Google to cheat, so here's a simple proof of concept using the Yahoo search API to even the playing field a little.
import re
import string
import readline
import textwrap
from yahoo.search.web import WebSearch
APP_ID = "IRCTriviaHelper"
def bullet(lines):
return ["\n".join(textwrap.wrap(line, 77, initial_indent=" - ", subsequent_indent=" ")) for line in lines]
def highlight(terms, text):
"""Highlight individual words, allowing for case differences in the highlighted string."""
stripchars = string.whitespace+string.punctuation
termpatterns = (r"\b%s\b" % term.strip(stripchars) for term in terms.strip().split(" "))
return re.sub("(?i)(%s)" % ("|".join(termpatterns)),
"\x1b[1m\x1b[36m\g<0>\x1b[0m",
text)
def get_summaries(query, exact=False):
search = WebSearch(APP_ID, query=query, type=("phrase" if exact else "all"), results=12)
resultxml = search.get_results()
results = resultxml.getElementsByTagName("Result")
summaries = []
for r in results:
summary = r.getElementsByTagName("Summary")[0]
if summary.hasChildNodes():
summaries.append(summary.firstChild.nodeValue)
return summaries
def main():
while True:
query = raw_input("Search query: ")
if not query: continue
exact = query.startswith("=")
if exact: query = query[1:]
print "-"*80
output = "\n".join(bullet(get_summaries(query, exact)))
print highlight(query, output)
print "-"*80
print
if __name__=="__main__": main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment