【问题标题】:Read from file Common Lisp [duplicate]从文件 Common Lisp 中读取 [重复]
【发布时间】:2017-06-09 20:12:17
【问题描述】:

我需要从文件中读取,但我遇到了一些代码问题。我必须像这样阅读 i 文件:

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))

我尝试过使用with-open-fileread-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)))

我该怎么做?谢谢

【问题讨论】:

    标签: file lisp common-lisp


    【解决方案1】:

    惯用的成语

    (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"))
    

    如果您担心内存使用,可以使用map-into 代替mapcar,甚至将line-as-list 作为参数传递给read-file-as-lines

    必读

    练习:在line-as-list 中使用loop,而不是在前面加上括号。 这样您就可以控制读取和处理 cmets 等对象的数量。

    解决方案string-tokens

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      相关资源
      最近更新 更多