Friday, March 13, 2009

A Source For Random Clever Text, or a Twitter API + PLT-Scheme Example

The internet radio station Boot Liquor, plays an eclectic mix of country music. Recently, I learned they broadcast their playlist over Twitter, to make it easy to see what's playing now.

Say what you will about the sound of country music, but the lyrics and even song titles are often wonderfully clever/ironic. So, watching the BootLiquor twitter feed, I couldn't help but think this would be a novel source for random text. (And why would you need this random text? No idea. It was just too interesting too ignore.)

With tongue firmly in cheek, I present the following following code which uses the Twitter API to pull down the latest data and spit it out in a list.

On a more serious note, you can never have too many examples of code parsing XML and doing something useful with the result. Here's the code - of course, you can generalize it to pull from any Twitter feed and do anything with the status updates. I can assure you, it's not limited to country music.

#lang scheme
(require net/url net/uri-codec  xml   scheme/match
         srfi/13  srfi/1    games/cards)

(provide/contract
 [random-clever-text (-> (listof string?))])

(define (status->text s)
  (string-trim (regexp-replace "^.* - " s "")))

(define (random-clever-text)
  (let ([xml (xml->xexpr (document-element
                          (read-xml 
                           (get-pure-port
                            (string->url "http://twitter.com/statuses/user_timeline/bootliquor.xml")))))])
    (shuffle-list (filter-map
                   (match-lambda
                     [(list-no-order 'status (list 'text '() junk text) _ ...) (status->text text)]
                     [else #f]) 
                   xml)
                  7)))

And here's the current results of running the program:

;; (random-clever-text)  =>
("Small Motors"
 "Baggage Claim (The Cowboy Song)"
 "My Heart Is A Ufo"
 "She Loves To Ride Horses"
 "Whiskey River"
 "Sunday Morning Coming Down"
 "Una Soda"
 "We Live A Long Time To Get Old"
 "Careless Coin"
 "Camile"
 "Adrift On The Sea"
 "Nothin' Makes A Man Go Crazy"
 "Going Home"
 "If The Drink Don't Kill Me"
 "Lucky Tonight"
 "All Downhill"
 "So Much Wine"
 "White Line Fever"
 "Let's Have A Party")

Hmmm, nothing particularly clever. Oh well, it was worth a try.

No comments:

Post a Comment