如何在 MIT/GNU Scheme 中读取文本文件?

How do I read a text file in MIT/GNU Scheme?

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

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

(call-with-input-file "my_file.txt"
  (lambda (port)
    (read port))) ; reads the file's contents

一般情况请参阅 file ports and on ports 上的参考手册。

Scheme 提供了几种读取文件的方法。您可以使用 'open/close' 样式,如下所示:

(let ((port (open-input-file "file.txt")))
  (display (read port))
  (close-input-port port))

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

(call-with-input-file "file.txt"
  (lambda (port)
    (display (read port))))

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

(with-input-from-file "file.txt"
                      (lambda ()
                        (display (read))))

您还需要阅读有关 Input Procedures 的部分。上面使用的 "read" 函数只从端口读取下一个 Scheme 对象。还有 read-char,read-line 等。如果你从文件中读取了所有内容,你会得到一些 eof-object 吗? will return 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