如何读取 MIT/GNU 方案中的文本文件?

Moh*_*oua 2 file-io scheme mit-scheme

我一直在学习 SICP,我想应用我迄今为止学到的一些概念。也就是说,积累、映射和过滤将帮助我提高工作效率。我主要使用 CSV 文件,并且我知道 MIT/GNU 方案不支持这种文件格式。但这没关系,因为我可以将 CSV 文件导出到 txt 文件,因为支持 txt 文件。

现在我阅读了手册的第 14 节输入/输出,坦率地说,缺乏具体的示例并不能帮助我入门。因此,我希望你们中的一些人能给我一个良好的开端。我有一个文本文件 foo.txt,其中包含国家列表的变量和观察结果。我只想将这个文件读入Scheme并操作数据。感谢您的帮助。任何示例代码都会有所帮助。

小智 5

Scheme 提供了几种读取文件的方法。您可以使用“打开/关闭”样式,如下所示:

(let ((port (open-input-file "file.txt")))
  (display (read port))
  (close-input-port port))
Run Code Online (Sandbox Code Playgroud)

您还可以使用 igneus 的答案,它将端口传递给过程,并在过程结束时自动为您关闭端口:

(call-with-input-file "file.txt"
  (lambda (port)
    (display (read port))))
Run Code Online (Sandbox Code Playgroud)

最后,我最喜欢的,更改当前输入端口以从文件中读取,运行提供的过程,关闭文件并在最后重置当前输入端口:

(with-input-from-file "file.txt"
                      (lambda ()
                        (display (read))))
Run Code Online (Sandbox Code Playgroud)

您还需要阅读有关输入过程的部分。上面使用的“read”函数仅从端口读取下一个Scheme对象。还有read-char、read-line等。如​​果你从文件中读取了所有内容,你会得到eof-object的东西吗?将返回 true on - 如果您循环遍历文件以读取所有内容,则很有用。

例如将文件中的所有行读取到列表中

(with-input-from-file "text.txt"
  (lambda ()
    (let loop ((lines '())
               (next-line (read-line)))
       (if (eof-object? next-line) ; when we hit the end of file
           (reverse lines)         ; return the lines
           (loop (cons next-line lines) ; else loop, keeping this line
                 (read-line))))))       ; and move to next one
Run Code Online (Sandbox Code Playgroud)