Skip to content

Instantly share code, notes, and snippets.

@zmcghee
Created December 19, 2011 15:38
Show Gist options
  • Save zmcghee/1497712 to your computer and use it in GitHub Desktop.
Save zmcghee/1497712 to your computer and use it in GitHub Desktop.
Grab lyrics from the song generator at phantomlyrics.org to tweet
"""
Script to grab lyrics from the song generator at phantomlyrics.org,
take 5 random verses from which you can choose, and make them ready
for Twitter.
"""
from httplib import HTTPConnection
from random import choice as random_choice
from sys import exit
from urllib import urlencode
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/html"}
params = urlencode({
"g": "rbh", # Rap/R&B
"e": random_choice([
"ang", # angry
"dep", # depressed
"hap", # happy
]),
})
try:
conn = HTTPConnection("phantomlyrics.org")
conn.request("POST", "/lyrics.php", params, headers)
response = conn.getresponse()
except:
print "Could not connect to phantomlyrics.org"
conn.close()
print "Closed connection"
exit()
try:
assert response.status == 200
data = response.read()
except AssertionError:
print "non 200 response from phantomlyrics"
exit()
except:
print "response from phantomlyrics was 200 but something else went wrong"
exit()
finally:
conn.close()
print "Closed connection"
try:
# get the song title & all the lyric pairs
song_title = ' -"' + data.split('<h1>')[1].split('</h1>')[0].strip() + '"'
body = data.split('<p class="lyrics')[1].split('">')[1].split('</p>')[0]
lines = body.replace("\n", "").split("<br />")
lyrics = [" /".join(lines[i:i+2]) for i in range(0, len(lines), 2)]
lyrics.sort(key=len)
lyrics.reverse()
for i in range(len(lyrics)):
if len(lyrics[i].strip()) <= (140 - len(song_title)):
safe = lyrics[i:]
break
# get five tweets to choose from
tweets = []
while len(tweets) < (len(safe) if len(safe) <= 5 else 5):
tweet = random_choice(safe).strip()
if tweet not in tweets:
tweets.append(tweet)
except:
print "error parsing the lyrics & getting a tweet"
exit()
print "Song title: %s" % song_title[2:]
for i in range(len(tweets)):
print "%s) %s" % (i+1, tweets[i])
tweet = None
while not tweet:
choice = raw_input('Enter choice: ')
try:
tweet = tweets[int(choice)-1] + song_title
except:
print "Invalid entry" # invalid entry
print "Your tweet is: %s" % tweet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment