How do I download and parse a csv file in Racket?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With