在普通的lisp中读取文件

use*_*858 7 file common-lisp

我如何阅读以下文件,其中包含带有标题和空格或制表符分隔的数据列,在常见的lisp中.

我还想将数据放入包含行的列表列表中.

另外,如何在常见的lisp中获得日期差异

ID YR MO DA YrM MoM DaM
100 2010 2 20 2010 8 30
110 2010 4 30 2010 9 12
112 2010 8 20 2010 10 20

Rai*_*wig 10

从流中读取包含NUMCOLS列的表的函数

它假定可以读取表中的项目READ.(PEEK-CHAR T ...)测试流中是否还有一些非空白文本.

(defun read-a-table (stream numcols)
  (cons (loop repeat numcols collect (read stream))
        (loop while (peek-char t stream nil nil)
              collect (loop repeat numcols collect (read stream)))))
Run Code Online (Sandbox Code Playgroud)

这是两个示例函数

一个从文件中读取一个表,另一个从字符串中读取一个表.

(defun read-a-table-from-file (file numcols)
  (with-open-file (stream file)
    (read-a-table stream numcols)))

(defun read-a-table-from-string (string numcols)
  (with-input-from-string (stream string)
    (read-a-table stream numcols)))
Run Code Online (Sandbox Code Playgroud)

让我们用字符串测试它:

(defun test ()
  (read-a-table-from-string "ID YR MO DA YrM MoM DaM
100 2010 2 20 2010 8 30
110 2010 4 30 2010 9 12
112 2010 8 20 2010 10 20"
                            7))
Run Code Online (Sandbox Code Playgroud)

执行测试

CL-USER 15 > (test)

  ((ID YR MO DA YRM MOM DAM)
   (100 2010 2 20 2010 8 30)
   (110 2010 4 30 2010 9 12)
   (112 2010 8 20 2010 10 20))
Run Code Online (Sandbox Code Playgroud)


Nie*_*jou 4

您可以使用READ-LINE从流中读取整行。如果您有文件名,则可以使用WITH-OPEN-FILE将流连接到文件。要将每一行作为列表的元素意味着使用 LOOP:

(环形
   for line = (读取行流 nil 'eof)
   直到(eq行'eof)
   收集线)

将每一行拆分为列需要在基本 Common Lisp 中进行一些工作,但是有一个cl-utilities包,其中包含一个名为 SPLIT-SEQUENCE 的函数,该函数可以将分隔字符串拆分为标记列表。

第一次搜索日期处理产生了http://common-lisp.net/project/cl-date-calc/index.html,它有一个 DELTA-DAYS 函数。