'''
bashquote.py
A simple python script to retrieve quotes from the
IRC quote database, www.bash.org.
'''
import urllib2
bash_str = 'http://www.bash.org/?'
rand_str = 'http://www.bash.org/?random'
findstr = ''
endstr = ''
def get_quote(num):
'''
Returns the specified quote from bash.org
'''
buff = "".join(urllib2.urlopen(bash_str+str(num)).readlines())
# Check to see if the quote was rejected
if (buff.find('Quote #'+str(num)+' was rejected') != -1):
return ''
if (buff.find('Quote #'+str(num)+ ' does not exist') != -1):
return ''
st = buff.find(findstr)
en = st + buff[st:].find(endstr)
quote = buff[st+len(findstr):en]
return dodgy_char_swap(quote)
def get_random(posrating=1):
'''
Returns a random quote from bash.org
Posrating = 1: Only select from quotes with rating > 0
= 0: Select from all quotes.
'''
if posrating != 1:
buff = "".join(urllib2.urlopen(rand_str+'1').readlines())
else:
buff = "".join(urllib2.urlopen(rand_str).readlines())
st = buff.find(findstr)
en = st + buff[st:].find(endstr)
quote = buff[st+len(findstr):en]
return dodgy_char_swap(quote)
def dodgy_char_swap(quote):
'''
Swaps out some dodgy characters, using the replace
method of the string class.
'''
quote = quote.replace('<br>','') # line break
quote = quote.replace('<','<') # less than
quote = quote.replace('>','>') # greater than
quote = quote.replace('\r\n','\n') # line feed
return quote
Tuesday, December 30, 2008
Using Python Urllib2 to retrieve quotes from bash.org
This is a simple (read brain dead) script I wrote to pull down specified quotes from bash.org (the IRC Quote Database). The script is below and should be fairly self explanatory. The only caveat is that you may not want to replace the web specific characters if you plan on using this to put random quotes onto a web page.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment