Home > Mobile >  how to covert a .csv file into a list of lists in Common-Lisp
how to covert a .csv file into a list of lists in Common-Lisp

Time:11-02

I am new to common-lisp and wanted to know how to convert a .csv file to a 2d list. I see that we can read the .csv file using:

(cl-csv:read-csv #P"filename.csv")

and you can convert into a 2d array by:

(defun read-2d-array (rows &rest args)
  (let* ((first-line (apply #'read-line args))
         (cols (1  (count #\space first-line)))
         (arr (make-array (list rows cols)
                          :element-type 'integer
                          :initial-element 0)))
    (loop for i below rows
          for line = first-line then (apply #'read-line args)
          for start = 0
          do (dotimes (j cols)
               (multiple-value-bind (number end)
                   (parse-integer line :start start
                                       :junk-allowed t)
                 (setf start end
                       (aref arr i j) number))))
    arr))

but my output looks like this after the above one:

#(#\c #\o #\l #\u #\m #\n #_ #\n #\a #\m #\e #, #\w #\i #\d #\t #\h #, #\l #\e #\n #\g #\t #\h #, #\v #\e #\r #\t #\i #\c #\a #\l #_ #\r #/ #\f #, #\s #\t #\i #\r #\r #\u #\p #\Return #\Newline #\c #\1 #, #\9 #, #\1 #\2 #, #" #\4 #- #\1 #\2 #\d #\i #\a #, #\4 #- #\1 #\0 #\d #\i #\a #" #, #\8 #- #\1 #\5 #\0 #\c #/ #\c #\Return #\Newline

but i want it to look something like : ((column_name width length vertical_r/f stirrup) (c1 9 12 4-12dia 8-150c/c))

Can someone help me with this? Thank you in advance.

CodePudding user response:

Given a file, /tmp/x.csv containing

column_name,width,length,vertical_r/f,stirrup
c1,9,12,4-12dia,8-150c/c

then using cl-csv:

> (read-csv #p"/tmp/x.csv")
(("column_name" "width" "length" "vertical_r/f" "stirrup")
 ("c1" "9" "12" "4-12dia" "8-150c/c"))
  • Related