Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download and parse a csv file in Racket?

How do I download and parse a csv file in Racket?

like image 265
soegaard Avatar asked Jun 04 '12 14:06

soegaard


1 Answers

Use get-pure-port to download the file, and use the Planet library (require (planet neil/csv)) to parse it.

The following example downloads and parses a csv file containing data on the size of the various Galapagos islands and how many species were found on each island.

#lang racket
(require (planet neil/csv:1:=7) net/url)

(define galapagos-url 
  (string->url
   "http://www.stat.washington.edu/~handcock/536/Data/galapagos.csv"))

(define make-galapagos-csv-reader
  (make-csv-reader-maker
   '((separator-chars              #\,)
     (strip-leading-whitespace?  . #t)
     (strip-trailing-whitespace? . #t))))

(define (all-rows url make-reader)
  (define next-row (make-reader (get-pure-port url)))
  (define (loop)
    (define row (next-row))
    (if (empty? row)
        '()
        (cons row (loop))))
  (loop))

(all-rows galapagos-url make-galapagos-csv-reader)

The first rows returned are:

'(("Island"
   "Observed.species"
   "Native.species"
   "Area(km^2)"
   "Elevation(m)"
   "Distance.nearest.island(km)"
   "Distance.Santa.Cruz(km)"
   "Area.adj.island(km^2)")
  ("Baltra" "58" "23" "25.09" "" "0.6" "0.6" "1.84")
  ("Bartolome" "31" "21" "1.24" "109" "0.6" "26.3" "572.33")
  ("Caldwell" "3" "3" "0.21" "114" "2.8" "58.7" "0.78")
like image 155
2 revs, 2 users 97% Avatar answered Sep 21 '22 23:09

2 revs, 2 users 97%