File 从公共Lisp文件读取
我需要读取一个文件,但我的代码有一些问题。我必须像这样阅读我的文件:File 从公共Lisp文件读取,file,lisp,common-lisp,File,Lisp,Common Lisp,我需要读取一个文件,但我的代码有一些问题。我必须像这样阅读我的文件: 1.0 4.5 4.555 6.43 4.0 5 ..... 6 3 ((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3)) 每行2个数字,由#\Space或#\Tab分隔(在文件中,我可以有大量行)。函数read必须返回如下列表: 1.0 4.5 4.555 6.43 4.0 5 ..... 6 3 ((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3)) 我曾尝试将与ope
1.0 4.5
4.555 6.43
4.0 5
.....
6 3
((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3))
每行2个数字,由#\Space
或#\Tab
分隔(在文件中,我可以有大量行)。函数read必须返回如下列表:
1.0 4.5
4.555 6.43
4.0 5
.....
6 3
((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3))
我曾尝试将与open file
、read line
和递归一起使用,但我在处理流等方面遇到了问题,无法以正确的方式将这些元素放入列表中
(with-open-file (in "foo.lisp"
:direction :input
:if-does-not-exist :error)
(myread in))
(defun myread (filename)
(let ((e (read-line filename nil ’eof))))
???
(cons (;;;numbers of current line;;;)(myread (filename)))
我该怎么做?谢谢通常的成语是
(defun read-file-as-lines (filename)
"Read file into a list of lines."
(with-open-file (in filename)
(loop for line = (read-line in nil nil)
while line
collect line)))
(defun line-as-list (line)
"Read all objects from the line as a list."
(read-from-string (concatenate 'string "(" line ")")))
(mapcar #'line-as-list (read-file-as-lines "mydata"))
如果您关心内存使用,您可以使用而不是甚至传递行作为列表
作为读取文件作为行
的参数
必读读物:
行作为列表中使用循环
,而不是在前面加括号。
通过这种方式,您可以控制读取和处理注释的对象数量&c
解决方案: