您可以利用Lisp解析器可供Lisp用戶使用的事實。這個數據的一個問題是一些值包含冒號,而在Common Lisp中使用包名稱分隔符。我編寫了一些可用的Common Lisp代碼來解決你的問題,但是我必須通過定義適當的包來解決上述問題。
這裏是你的例子在你的問題留出了代碼,那當然必須要延長(以下即是在它已經使用了相同的模式)的一切:
(defpackage #:thous
(:export #:5-10 #:20+))
(defpackage #:private
(:export #:roman-catholic))
(defstruct (college (:conc-name nil))
(name "")
(state "")
(location "")
(control "")
(no-of-students ""))
(defun data->college (name data)
(let ((college (make-college :name (write-to-string name :case :capitalize))))
(loop for (key value) in data
for string = (remove #\| (write-to-string value :case :downcase))
do (case key
(state (setf (state college) string))
(location (setf (location college) string))
(control (setf (control college) string))
(no-of-students (setf (no-of-students college) string))))
college))
(defun read-data (stream)
(loop for (def-instance name . data) = (read stream nil nil)
while def-instance
collect (data->college name data)))
(defun print-college-as-csv (college stream)
(format stream
"~a~{,~a~}~%"
(name college)
(list (state college)
(location college)
(control college)
(no-of-students college))))
(defun data->csv (in out)
(let ((header (make-college :name "College"
:state "state"
:location "location"
:control "control"
:no-of-students "no-of-students")))
(print-college-as-csv header out)
(dolist (college (read-data in))
(print-college-as-csv college out))))
(defun data-file-to-csv (input-file output-file)
(with-open-file (in input-file)
(with-open-file (out output-file
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(data->csv in out))))
主要功能是data-file-to-csv,加載此代碼後可以在Common Lisp REPL中使用(data-file-to-csv "path-to-input-file" "path-to-output-file")
調用。
編輯:一些額外的想法
它實際上會更容易些,而不是增加包裝的定義對於所有的值用冒號,做一個正則表達式搜索和替換過來的數據添加身邊所有的引號(「)值。這將使Lisp語言解析他們作爲字符串的時候了。在這種情況下,該行for string = (remove #\| (write-to-string value :case :downcase))
可能被刪除,string
可以在case
聲明的所有行與value
取代。
由於數據的高規律性,實際上甚至不需要正確解析Lisp定義,而是,你可以用正則表達式提取數據。一種特別適合基於正則表達式的文本文件轉換的語言應該適用於AWK或Perl這樣的工作。
通常適用於您的Lisp數據的軟件是否可用?如果你可以使用它的'def-instance'定義,這將爲你省去編寫'def-instance'或者自己解析這些調用的麻煩。 –
我收到了這種格式的數據,我不知道它們來自哪裏。我的任務是將這個lisp方案轉換成可以用RapidMiner處理的某種表格數據。我真的很想避免自己編寫一些解析器/轉換器:) – svobol13