(hello

‘world)

I’m feeling lucky.

One of the first Common Lisp programs I’ve written. It returns the URL that Google’s “I’m Feeling Lucky” redirects to, or nil if not found. It uses url-encode from http://weitz.de/cl-ppcre/#regex-replace-all.

(defpackage :simple-google
    (:use :common-lisp
	  :drakma   ; For google-search
	  :cl-ppcre) ; For url-encode
  (:export :google-search))

(in-package simple-google)

;;; From http://weitz.de/cl-ppcre/#regex-replace-all
(let ((url-regex (cl-ppcre:create-scanner "[^a-zA-Z0-9_\\-.]")))
  (defun url-encode (string)
    "URL-encode a string."
    ;; won't work for Corman Lisp because non-ASCII characters aren't 8-bit there
    (flet ((convert (target-string start end match-start match-end reg-starts reg-ends)
             (declare (ignore start end match-end reg-starts reg-ends))
             (format nil "%~2,'0x" (char-code (char target-string match-start)))))
      (cl-ppcre:regex-replace-all url-regex string #'convert))))

(defun google-search (search-string)
 "Returns the URL that I'm Feeling Lucky redirects to, or nil if not found."
  (progn
    (drakma:http-request
     (format nil "http://www.google.com/search?hl=en&q=~A&btnI=I%27m+Feeling+Lucky"
	     (url-encode search-string)) :user-agent :firefox)
    (let ((result (get-output-stream-string drakma:*header-stream*)))
     (if (cl-ppcre:scan-to-strings "Location:\\s(.*)" *result*)
       (subseq (cl-ppcre:scan-to-strings "Location:\\s(.*)" result) 10) ; Was found
       (nil))))) ; Wasn't found

January 6, 2008 - Posted by | Common Lisp, web

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: